简体   繁体   中英

setState inside a static method

I want to set the state of one component from another component using setState method as it seems to involve less coding, however I have come to know that I can't use the this keyword in a static method which has created a problem for me. I would like to know another get around of this problem. help would really appreciated.

First component

class First extends Component {

    filterByLocation(loc) {
        const filteredData = this.state.passedInfo.filter(({area}) => area === loc);
        this.setState({members: filteredData})
    }

}

Second component

class Second extend Component {

    renderSuggestion() {

        <TouchableOpacity 
            onPress = {()=> this.setState({location}, () => {
                First.filterByLocation(this.state.location);
            })}>

            <Text> {"Click Me"}</Text>
        </TouchableOpacity>
    }
}

I initially considered this a comment, but really, it's an answer:

One component should never set the state of another component, even if it had access to the component instance (and thus to setState ). It certainly can't do so without access to the component instance.

Instead:

  • Lift state up and have it passed to the component as props, or
  • Use portals and again pass the state as props (note: not entirely sure portals are supported in React Native, though a search turns up projects providing similar functionlity) , or
  • Use context (which is supported in React Native)

...or possibly any of several other things. In your specific scenario, lifting state up seems like the right thing.

Why not to pass whole this object to your method like:

    <TouchableOpacity 
        onPress = {()=> this.setState({location}, () => {
            Home.filterByLocation(this, this.state.location);
        })}>

        <Text> {"Click Me"}</Text>
    </TouchableOpacity>

Filter method:

    filterByLocation(context, loc) {
        const filteredData = context.state.passedInfo.filter(({area}) => area === loc);
        context.setState({members: filteredData})
    }

For sure it is not a good practice, it should solve the problem but should not be overused.

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