首页 > 解决方案 > 如何在使用 mapStateToProps 设置道具时更新状态?

问题描述

defaultValue使用 Redux 设置的道具设置文本字段的mapStateToProps.

当文本字段更改(使用 检测onChange={...})时,我调用setState以捕获用户输入。

问题是,目前,如果文本字段没有改变,setState则永远不会被调用。如果用户提交表单,则defaultValue不会声明,因此会提交一个空字符串。

许多人推荐使用componentWillReceiveProps,但此方法已被弃用。

标签: reactjsreduxmaterial-ui

解决方案


通过类组件的getDerivedStateFromPropssetStateuseEffect功能组件的回调调用为组件的状态提供值 :

const [state, setState] = useState(props.propFromRedux)
useEffect(() => setState(props.propFromRedux), [props.propFromRedux])


推荐阅读