reactjs - 如何在 React 16.x 中比较以前的上下文和当前的上下文?
问题描述
有没有办法在消费者子组件的生命周期方法中将先前的上下文值与当前的上下文值进行比较?
如果没有办法做到这一点,是否有任何其他解决方法或替代解决方案?
仅供参考:我正在使用反应 v16.8.1
解决方案
使用 HOC:
const withContext = Wrapped => props => (
<SomeContext.Consumer>
{value => <Wrapped {...props} contextValue={value}/>}
</SomeContext.Consumer>
);
const MyComponent = withContext(class extends React.Component {
...
componentDidUpdate(prevProps) {
if (prevProps.contextValue !== this.props.contextValue) {
...
}
}
...
});
使用钩子:
function MyComponent(props) {
...
const contextValue = useContext(SomeContext);
const [oldContextValue, saveContextValue] = useState(contextValue);
useEffect(() => {
console.log(oldContextValue, contextValue);
saveContextValue(contextValue);
}, [contextValue]);
...
}
请注意,useEffect
仅在第一次渲染和contextValue
更改时运行。所以如果你真的不需要 oldcontextValue
来做某事,你就不需要useState
.
推荐阅读
- sql - 在 and SQL 中计算 and
- r - topgo lapply 而不是 R 中的 for 循环
- python - AttributeError:模块“h5py”没有属性“文件”
- ruby-on-rails - 使用 ssl 运行 rails 服务器?(彪马)
- r - 右连接 R 中的两个数据集不适用于 dplyr 和 base R
- excel - 选择范围并复制
- xojo - TabPanel 和滚动
- python - AssertionError:在 Keras 中使用 multi_gpu_model() 时无法计算输出张量
- javascript - 将 TSS 与 Javascript(无 TS)一起使用时,JSX 内在元素上不存在获取属性
- apache-zookeeper - Zookeeper 临时节点创建顺序