问题:
react 中传递给子组件的 props 是否都应该由父组件控制。
场景:
模板消息弹框子组件,定义了所有需要的 state ( sendName,reveiveName,content,...);
父组件调用子组件时,传递(不是一定的) content props 给子组件,子组件在 static getDerivedStateFromProps 中根据 content props 更新 content state。
问题:
子组件有必要定义这些 state 吗?还是都由父组件传递 props 进去;
子组件在 static getDerivedStateFromProps 中根据 content props 更新 content state 时,会导致子组件的 state 无法更新了,是我判断条件写的有问题,但是不知道怎么改进下:
static getDerivedStateFromProps(props, state) { const { content } = props; if (state.content !== content) { return { content, }; } else { return null; } } 还有其他场景,比如编辑时,我也是把编辑页面写成一个组件,在里边定义了所有的 state,父组件传递 props 进去后进行合并(不知道这样操作对不对),总感觉有点问题,但没有啥好的想法,接触 react 有点短。
求解惑,不胜感激。
