简体   繁体   中英

React native how to listen context change in lifecycle

Overview

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 {}

Code

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

Reason

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.

Code

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;

⚠️Note

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM