【问题标题】:Redux receiving props delay after dispatch calling from componentDidMount从 componentDidMount 调度调用后 Redux 接收道具延迟
【发布时间】:2020-04-08 02:00:24
【问题描述】:

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

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 发生 props 没有立即收到时,因为 API 响应有延迟。从 API 收到数据后,能否请您帮助访问道具。

谢谢。

【问题讨论】:

  • 从 api 获取自然需要时间,尝试为您的组件添加加载器,直到从 api 获取数据。
  • const accInfo = this.props.accounts 在收到数据后仍然无法访问。响应后如何访问状态数据。
  • 您似乎没有将数据写入redux store。您能描述一下您何时从响应中写入数据吗?
  • 如果一切设置正确,则应在更新 redux 状态时更新 Props。仔细检查你的减速器。
  • 我已更新reducer 代码。我的reducer js 文件有什么问题吗

标签: reactjs redux redux-thunk


【解决方案1】:

这里发生了什么:

  1. cDM 被调用,动作被调度。
  2. 如果 action creator 是同步的(只是一个普通的 action + 没有任何异步操作的直接 reducer)状态将被更新
  3. render() 发生在以前的道具(旧状态)
  4. redux 的store.subscribe() 使包装器(由connect 创建)重新计算所有mapStateToProps/mapDispatchToProps
  5. 由于步骤#3 返回了不同的值,包装器使用新的props 重新呈现您的组件
  6. render() 发生在新道具上

事实上,你的动作创建者本质上是异步的,开关 #2 和 #3 与它们的位置是异步的。但无论如何,您的第一次渲染将使用旧的存储值。

所以你最好相应地处理它(比如检查某个对象是否不再是undefined 或使用全新的optional chaining 来避免“无法读取属性... of null”)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-26
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    • 2018-04-30
    • 2018-07-21
    相关资源
    最近更新 更多