我有一个reactjsapp,这是我主要组件的一部分:
render() {
console.log('main=this.props.data', this.props.data);
console.log('main=this.props.userData', this.props.userData);
return (
<section className="app container">
<PacksContainer packsData={this.props.userData} ></PacksContainer>
<div className="row">
<section className="container">
</section>
</div>
</section>
);
}
}
const mapStateToProps = function (store) {
return {
data: store.datas,
userData: store.apiData
};
};
export default connect(mapStateToProps)(MainLayout);
来自ajax调用的数据被注入到props中,状态记录器表示状态已经从异步响应中成功填充。但是render()不会再次触发并且props.data不会更新,保持未定义?我该如何重新渲染该组件?
答案 0 :(得分:1)
使用react-redux。你必须从reducer更新状态。
let action = {type: 'YOUR_ACTION_TYPE', payload: userData}
store.dispatch(action)
来自您创建了redux“store”的应用索引
const store = createStore(reducer, initialState, ...);
你的商店需要一个reducer,它是一个带(state,action)和return nextState
的函数const reducer = (state, action) => {
if(action.type === 'YOUR_ACTION_TYPE') {
// update new state
return Object.assign({}, ...state, {userData: action.payload})
}
//..
}
当状态改变时,您连接的组件将更新
// this will be called when you dispatch any action and the component will update with new props
const mapStateToProps = function (state) { // new state returned from reducer
return {
data: state.datas,
userData: state.apiData
};
};