如何让我的组件在 ajax 调用后重新呈现?
How to let my component rerender after ajax call?
我有一个 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 调用的数据被注入到道具中,状态记录器表示状态已从异步响应成功填充。但是 render() 不会再次触发并且 props.data 不会更新,保持未定义状态?如何重新渲染组件?
使用 react-redux。你必须从 reducer 更新状态。
调度操作
let action = {type: 'YOUR_ACTION_TYPE', payload: userData}
store.dispatch(action)
reducer 获取状态,然后动作 return 新状态
来自您创建 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
};
};
我有一个 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 调用的数据被注入到道具中,状态记录器表示状态已从异步响应成功填充。但是 render() 不会再次触发并且 props.data 不会更新,保持未定义状态?如何重新渲染组件?
使用 react-redux。你必须从 reducer 更新状态。
调度操作
let action = {type: 'YOUR_ACTION_TYPE', payload: userData}
store.dispatch(action)
reducer 获取状态,然后动作 return 新状态
来自您创建 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
};
};