reactjs - 如何在使用 mapStateToProps 设置道具时更新状态?
问题描述
我defaultValue
使用 Redux 设置的道具设置文本字段的mapStateToProps
.
当文本字段更改(使用 检测onChange={...}
)时,我调用setState
以捕获用户输入。
问题是,目前,如果文本字段没有改变,setState
则永远不会被调用。如果用户提交表单,则defaultValue
不会声明,因此会提交一个空字符串。
许多人推荐使用componentWillReceiveProps
,但此方法已被弃用。
解决方案
通过类组件的getDerivedStateFromProps或setState
从useEffect
功能组件的回调调用为组件的状态提供值 :
const [state, setState] = useState(props.propFromRedux)
useEffect(() => setState(props.propFromRedux), [props.propFromRedux])
推荐阅读
- powerbi - 如何在散点图中显示点的轨迹,而不是让它在功率双散点图中消失?
- java - 对HashMap java的绝对值求和
- compilation - 编译器真的可以识别时间复杂度的改进并在幕后实现它们吗?
- django - 如何在 django 模板中显示模型数据?
- c# - EntityState.Deleted 和 Remove() 方法之间的真正区别是什么?何时使用它们中的每一个?
- javascript - 将 API 请求中的 PDF 流字节转换为 base64(Javascript *无库!*)
- hololens - HoloLens 2 滞后的 TCP 客户端
- excel - VBA unprotect-blank 进入和退出处理
- visual-studio - 用于运行 Visual Studio 2019 的推荐 VM
- c# - 任务是否可能由于您的 AppDomain 之外的事件而出错?