Use React.createContext()
replace props
, but also want to know what changed in child component.So I use lifecycle componentWillReceiveProps
or the other who has nextContext
argument.
And now, when I setState
value and console nextContext
or this.context
,but get nothing {}
Provider
//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>
)
}
}
Consumer
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>
)
}
}
🎉I solved it.
class need manual assign ContextObject contextType
reference https://reactjs.org/docs/context.html#classcontexttype
The contextType
property on a class can be assigned a Context object created by React.createContext()
. This lets you consume the nearest current value of that Context type using this.context
. You can reference this in any of the lifecycle methods including the render function.
commit
- 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>
Consumer
Menus.contextType = MenusContext;
shouldComponentUpdate
cant listen context change only, so when context change ,UI will change as well even if return false
in shouldComponentUpdate
life.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.