接收数据后状态不会立即更新
Accounts.js 像这样
class Accounts extends Component {
componentDidMount()
{
this.props.dispatch(fetchAccountsAction())
}
render(){
const accInfo = this.props.accounts // Not getting data immediately
return (
<Details accInfo = {accInfo} />
)
}
}
const mapStateToProps = (state, ownProps) => {
console.log('state',state);
return {
accounts:state.accounts
}
}
export default connect(mapStateToProps)(Accounts)
Action.js 像这样
const fetchAccountsAction = () => {
return async (dispatch) => {
const res = await fetch(url, {
method: "POST",
headers: {
'Content-type': 'Application/json',
'Authorization': token,
},
body: JSON.stringify(data)
});
const data = await res.json()
if (data) {
dispatch(fetchAccounts(data))
}
}
}
export function fetchAccounts(accounts)
{
console.log('accounts',accounts) // Am getting data here
return {
type: FETCH_ACCOUNTS,
accounts : accounts
}
}
Reducer.js 像这样
const initialState = {
accounts : [],
error:null
}
export function accountsReducer(state=initialState,action) {
switch(action.type){
case FETCH_ACCOUNTS:
return {
...state,
accounts:action.accounts
}
default:
return state
}
}
componentDidMount
发生时,由于API响应延迟,道具无法立即收到。从API接收数据后,能否请您提供有关props访问的帮助。
谢谢。
答案 0 :(得分:0)
这里发生了什么
cDM
被调用,动作被调度。 render()
与以前的道具(旧状态)一起发生store.subscribe()
进行包装(由connect
创建)以重新计算所有mapStateToProps
/ mapDispatchToProps
props
重新呈现了您的组件render()
与新道具一起发生事实上,您的动作创建者由于其自然开关#2和#3与他们的位置不同步。但是无论如何,您的第一个渲染将使用旧的存储值。
因此,您最好相应地进行处理(例如检查某个对象是否不再是undefined
或使用全新的optional chaining来防止“无法读取null属性...”)