gpt4 book ai didi

javascript - React Native 如何监听生命周期中的上下文变化

转载 作者:行者123 更新时间:2023-11-30 06:17:30 25 4
gpt4 key购买 nike

概览

使用React.createContext()替换props,但也想知道子组件发生了什么变化。所以我使用生命周期componentWillReceiveProps或者另一个有 nextContext 参数。

现在,当我setState 值并控制 nextContextthis.context 时,却什么也得不到{}

代码

提供者

//I create a context to transmit data
const {Provider,Consumer} = React.createContext({visible:true});

export default class extends Component {
constructor(props){
super(props);
this.state={
visible:false,
};
}

toggleMenus=()=>{
let visible = this.state.visible;
this.setState({visible:!visible})
};



render(){
return (
<Provider value={{visible:this.state.visible}}>
<View style={{flex:1}}
onStartShouldSetResponder={this.toggleMenus}
>
<Menus />
</View>
</Provider>
)
}
}

消费者

class Menus extends React.Component {
componentWillReceiveProps(nextProps, nextContext) {
console.log(nextProps, nextContext, this.context)//{},{},{}
//I cant get nextContext to listen context change
}

shouldComponentUpdate(nextProps, nextState, nextContext) {
return false //UI still update
}

render(){
return (
<Consumer>
{({visible})=>
<Text>{visible?1:2}</Text>
}
</Consumer>
)
}
}

最佳答案

🎉我解决了。

类需要手动分配 ContextObject contextType

原因

reference https://reactjs.org/docs/context.html#classcontexttype

可以为类的 contextType 属性分配一个由 React.createContext() 创建的 Context 对象。这使您可以使用 this.context 使用该上下文类型的最接近的当前值。您可以在任何生命周期方法中引用它,包括渲染函数。

代码

提交

- const {Provider,Consumer} = React.createContext({visible:true});
+ const MenusContext = React.createContext({visible:true});

- <Provider value={{visible:this.state.visible}}>
+ <MenusContext.Provider value={{visible:this.state.visible}}>

- <Consumer>
+ <MenusContext.Consumer>

消费者

Menus.contextType = MenusContext;

⚠️注意

shouldComponentUpdate 不能只监听上下文变化,所以当上下文变化时,即使 return falseshouldComponentUpdate 生命中,UI 也会改变。

关于javascript - React Native 如何监听生命周期中的上下文变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55252820/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com