本文介绍了直接从 redux 存储填充输入字段中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以将我的输入字段值设置为 redux 存储值吗?或者我可能需要为此将道具复制到我的本地状态?

Can I set my input fields value to redux store value? Or may I need to copy the props to my local state for this?

<input
      placeholder={props.placeholder}
      value={props.value}
 />

props.value 来自 react-redux 的 Connect.

props.value is coming from react-redux's Connect.

但是我不能改变input的值,我认为这是因为props是只读的

But I can't change the value of input, I think this is because props is read only

推荐答案

你可以这样设置值,没错.要更改此类输入值,您必须添加 onChange 事件处理程序,该事件处理程序将调度更新 Redux 存储中相应值的操作(检查 React 关于受控表单字段的文档):

You can set value that way, it's correct. To change such input value you have to add onChange event handler that will dispatch an action updating corresponding value in Redux store (check React doc about controlled form fields):

<input
      placeholder={props.placeholder}
      onChange={(event) => props.updateValueInRedux(event.target.value)}
      value={props.value}
 />

在上面的例子中,updateValueInRedux 应该是一个从 Redux connect 传递给组件的函数,作为 mapDispatchToProps 参数的属性,它将调度一个动作更新还原状态.它应该是这样的:

In above example the updateValueInRedux should be a function passed to component from Redux connect as property of mapDispatchToProps argument that will dispatch an action updating Redux state. It should look like that:

const mapStateToProps = {
    ...
}

const mapDispatchToProps = (dispatch) => {
    return {
        updateValueInRedux: (value) => {
            dispatch(someReduxUpdateAction(value));
        }
    }
};

const MyConnectedComponent = connect(
    mapStateToProps,
    mapDispatchToProps
)(MyComponent);

这篇关于直接从 redux 存储填充输入字段中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 22:04