Redux在从componentDidMount调度调用后接收道具延迟

时间:2019-12-15 09:06:19

标签: reactjs redux redux-thunk

接收数据后状态不会立即更新

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访问的帮助。

谢谢。

1 个答案:

答案 0 :(得分:0)

这里发生了什么

  1. cDM被调用,动作被调度。
  2. 如果动作创建者处于同步状态(只是一个普通动作+没有任何异步操作的平整减速器)状态就会被更新
  3. render()与以前的道具(旧状态)一起发生
  4. redux的store.subscribe()进行包装(由connect创建)以重新计算所有mapStateToProps / mapDispatchToProps
  5. 由于第3步返回了不同的值,包装器使用新的props重新呈现了您的组件
  6. render()与新道具一起发生

事实上,您的动作创建者由于其自然开关#2和#3与他们的位置不同步。但是无论如何,您的第一个渲染将使用旧的存储值。

因此,您最好相应地进行处理(例如检查某个对象是否不再是undefined或使用全新的optional chaining来防止“无法读取null属性...”)