【问题标题】:Flux/utils: How to access to props in the calculateState method?Flux/utils:如何在 calculateState 方法中访问 props?
【发布时间】:2023-03-08 13:44:01
【问题描述】:

container 组件中,如何在基于this.propscalculateState 静态方法中从存储中获取状态?

【问题讨论】:

    标签: reactjs reactjs-flux flux


    【解决方案1】:

    容器无法访问 props 默认情况下容器无法访问任何 props。这既是出于性能原因,也是为了确保容器是可重用的,并且 props 不必在整个组件树中进行线程化。在某些有效情况下,您需要根据道具和商店的状态来确定您的状态。在这些情况下,将选项 {withProps: true} 作为第二个参数传递给 create()。这会将组件 props 作为 calculateState() 的第二个参数公开。

      class CounterContainer extends Component {
    
           static calculateState(prevState,props) {
             return {
               counter: CounterStore.getState(props.id),
            };
          }
    
            render() {
               return <CounterUI counter={this.state.counter} />;
            }
      }
    
    const container = Container.create(CounterContainer, {withProps:true});
    

    【讨论】:

    • 我已经在store上定义了一个getStateById方法,问题是我无法访问this.props.params.id里面的this.props.params.id例如静态方法。
    • 我不熟悉新的静态函数声明,但我猜它实例化了自己的范围,如果我的建议有效,请告诉我我很好奇
    • 没用,你不能在类范围内这样声明self
    • 也许有吸气剂?更新答案
    • 你不能通过静态方法访问getter,也不能在类范围内声明self(语法方法:unexpected token)。
    猜你喜欢
    • 2018-01-09
    • 2016-08-30
    • 2020-09-17
    • 2016-05-06
    • 2020-12-13
    • 1970-01-01
    • 2019-12-28
    • 2020-07-31
    • 2022-01-08
    相关资源
    最近更新 更多