简体   繁体   English

静态方法中的setState

[英]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. 我想使用setState方法设置一个组件与另一个组件的状态,因为这似乎涉及较少的编码,但是我知道我不能在静态方法中使用this关键字,这给我带来了问题。 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 ). 即使一个组件可以访问该组件实例(从而可以访问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 使用门户并再次将状态作为道具传递(注意:尽管搜索会发现提供类似功能的项目,但不能完全确定React Native是否支持门户) ,或者
  • Use context (which is supported in React Native) 使用上下文 (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. 为了确保这不是一个好的做法,它应该可以解决问题,但又不应过度使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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