我不熟悉助焊剂并起反应,我想知道如何从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.
}
您需要使用生命周期方法来了解componentDidMount
概述的here方法>
要初始化localstate,您应该使用构造函数方法(也可以使用static方法,但是jsfiddle会引发错误。
要显示初始状态,可以在componentDidMount
中使用this.state
登录。
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>