【问题标题】:accessing state inside calculatestate from componentdidmount从componentdidmount访问calculatestate中的状态
【发布时间】:2020-09-17 05:44:20
【问题描述】:

我是 Flux 和 react 的新手,我想知道如何访问 calculatestate() 中的状态 componentdidmount()?

如何访问 componentdidmount() 中的事件状态?我想遍历事件,然后为每个事件运行一个查询,这反过来又更新另一个商店。

static getStores() {
  return [SomeStore];
}
static calculateState(prevState, props) {
  const somestore = SomeStore.getState();

  return {
    events: SomeStore.getState(),
  };
}

componentdidmount(){

  //this.state.events;
  //need to do some query based on the events
  //this query will update another store.
}

【问题讨论】:

  • 这里有更新吗?
  • 目前没有更新。我尝试使用 Flux 和 Flux 容器创建一个简单的 React 应用程序,但在使用 Flux 容器时它给了我一个错误。像这样的东西:你需要声明 .... 使用 new 关键字..

标签: reactjs flux


【解决方案1】:

您需要使用生命周期方法来理解componentDidMount 方法,其中概述了here

要初始化localstate,应该使用constructor方法(也可以使用static,但是jsfiddle会报错。

要显示初始状态,您可以使用this.statecomponentDidMount 内登录。

const someStore = ["event"];

class TodoApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = { events: someStore };
  }

  // if you want to change state based on props
  shouldComponentUpdate(nextProps, nextState) {
    // change state if you want here
    if (this.state.events.length !== nextState.events.length) {
      console.log(this.state, nextState)
      return true // update
    }

    return false
  }

  // get initial state
  componentDidMount() {
    console.log(this.state.events);
  }

  render() {
    return (
      <div>
        <span>example</span>
        <button onClick = {() => {
          this.setState(state => {
            return {
              events: [...state.events, "new event"]
            }
          })
        }}>Add Event</button>
        
        <div>
          events: { JSON.stringify(this.state.events) }
        </div>
      </div>
    )
  }
}

ReactDOM.render(<TodoApp />, document.querySelector("#app"));
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>

【讨论】:

  • 正如您所描述的,我可以做到,但是您如何从calculateState() 获取状态?它在render 方法中运行良好,但在componentdidmount() 中却不行。你的例子没有实现flux/redux。
  • flux 是一种设计模式,其中状态会根据您设置初始状态的方式进行更新,并且对状态的任何更新都是不可变的
  • redux 未包含在您的示例中,如果您想要一个 redux 解决方案 - 您应该包含一个代码框示例 -
  • 您的 redux 状态,您将其映射到组件道具。您的反应组件状态与 redux 状态无关,它们是不同的。如docs 所说,对于映射,您可以使用redux 的connect 函数。像 connect(mapStateToProps)(MyComponent) 其中 mapStateToProps 是一个接收 redux 状态作为参数的函数
  • 我想说 - 就像,如果我们获得有关 redux 状态如何连接的更多信息,我们可以详细说明,但应该允许 OP 解释更多 - 我认为如果没有更多上下文我可以扩展答案,很高兴稍后删除答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-20
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 2017-04-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多