Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 通过上下文API设置子组件中父组件的状态(在子组件中用作道具)-不会触发componentDidUpdate_Reactjs - Fatal编程技术网

Reactjs 通过上下文API设置子组件中父组件的状态(在子组件中用作道具)-不会触发componentDidUpdate

Reactjs 通过上下文API设置子组件中父组件的状态(在子组件中用作道具)-不会触发componentDidUpdate,reactjs,Reactjs,父组件--App用传递App状态的Context.Provider包装 子计数器组件通过HOC呈现,其参数是从App组件传递的状态变量 单击子组件-通过上下文API更改该状态变量 子组件实际上会重新渲染 但是,componentdiddupdate不会被触发 为什么? 我怀疑这与React的肤浅比较有关 在仍然使用此模式的情况下,如何使componentdiddupdate触发 代码示例(也在代码笔上:) const StateContext=React.createContext(); con

父组件--
App
用传递
App
状态的
Context.Provider
包装
计数器
组件通过HOC呈现,其参数是从
App
组件传递的状态变量
单击子组件-通过上下文API更改该状态变量
子组件实际上会重新渲染 但是,
componentdiddupdate
不会被触发
为什么?
我怀疑这与React的肤浅比较有关
在仍然使用此模式的情况下,如何使
componentdiddupdate
触发

代码示例(也在代码笔上:)

const StateContext=React.createContext();
const StateProvider=StateContext.Provider;
const renderChild=num=>{
类计数器扩展了React.Component{
静态上下文类型=StateContext;
构造函数(道具、上下文){
超级(道具、背景);
}
componentDidUpdate(prevProps){
console.log(“组件更新”);
}
点击=()=>{
this.context.setAppState({counter:this.context.appState.counter+1});
}
render(){
返回{this.props.counter}
}
}
返回
}
类应用程序扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
柜台:0
};
}
render(){
返回(
{this.setState(newState)}
}}>
{renderChild(this.state.counter)}
);
}
}
ReactDOM.render(
,
document.getElementById('root'))
);

问题在于每次渲染时都会调用
renderChild

因此,
Counter
实际上是在每个渲染上卸载的,而不是像您期望的那样得到更新,因此
diddupdate
生命周期永远不会生效

const renderChild = num => {
  class Counter extends React.Component {
    // Called on every render
    componentDidMount() {
      console.log('mounted on every render');
    }

    ...
    render() {
      return (...);
    }
  }
  return <Counter counter={num} />;
};
const renderChild=num=>{
类计数器扩展了React.Component{
//在每次渲染时调用
componentDidMount(){
console.log(“安装在每个渲染器上”);
}
...
render(){
回报率(…);
}
}
返回;
};


要修复它,您需要在其父组件中装入
计数器一次。

正确。谢谢我需要记住不要从
render
调用HOC函数!
const renderChild = num => {
  class Counter extends React.Component {
    // Called on every render
    componentDidMount() {
      console.log('mounted on every render');
    }

    ...
    render() {
      return (...);
    }
  }
  return <Counter counter={num} />;
};