【问题标题】:Set local state according to Mobx state根据 Mobx 状态设置本地状态
【发布时间】:2019-01-25 16:57:59
【问题描述】:

在组件中,我想根据Mobx状态打开一个modal。但我对此感到困惑。

在 Mobx 中,我有一个返回报告的计算函数。

@observable report= null;
@computed get getErrorReport(){return this.report}

并且在组件中,如果出现错误,我想打开一个模式,为此我需要设置模式标志。

render() { 
    const { getErrorReport } = this.props.myStore!;
    if(getErrorReport) {this.setState({modalOpen:true})}
    .....
}

当然,这个更新是错误的。通常在这些情况下,我们需要setState 渲染应该是什么方法?

【问题讨论】:

    标签: reactjs mobx setstate mobx-react


    【解决方案1】:

    您可能希望以这种方式构建您的代码。

    class MyStore {
        @observable report = null;
        // You do not need a @computed here just to return a property - access it 
        // directly
    }
    
    
    @inject('myStore')  // myStore is an instance of MyStore that you passed to Provider
    @observer // observer will trigger a rerender if any observable prop change (report 
              // in your case)
    class MyReactComponent extends React.Component {
    
    // so you do not need a set state here 
    
        render() {
             // Your modal component may differ, this is example
            return (<Modal isOpened={this.props.myStore.report} />)
        }
    
    }
    
    

    【讨论】:

    • 谢谢,但在这种情况下,我必须清空报告以关闭模式。其他一些组件需要这些信息。我希望组件单独管理其 Modal
    • 您的要求有争议。如果其他一些组件需要report,并且您无法清空它 - 那么最好绑定report的某些属性。在渲染中调用setState(在渲染阶段)是 React 中的反模式。主要规则 - 中继状态,从状态数据中获取渲染组件所需的数据,在 render 中使用它
    【解决方案2】:

    根据 mobx 文档,如果你想要一个变量来触发你的渲染,你应该使用 observable,所以在这种情况下你看起来根本不需要使用 state,因为 observable 会触发渲染并且在你的渲染函数中你应该询问报告是否不为空,如果是,只需打开您的模式而不更改您的状态。 我错过了什么吗?

    【讨论】:

    • 是的,我知道这些事情,但这不是我要寻找的。希望组件控制它是模态的而不是商店
    • 如果您有特殊原因这样做,您可以检查 componentDidUpdate 上的报告是否不为空,然后触发 setState 但要注意无限循环
    猜你喜欢
    • 1970-01-01
    • 2017-06-11
    • 1970-01-01
    • 2017-07-18
    • 2021-03-28
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多