【问题标题】:Why the redux state is undefined after my action call inside componentDidMount?为什么我在 componentDidMount 中的操作调用后 redux 状态未定义?
【发布时间】:2020-11-05 22:22:38
【问题描述】:

我有一个问题困扰了我一段时间,所以在这里...我正在尝试从我的 API 中获取详细信息,因此我创建了一个异步操作创建器,并且通常这样做我在componentDidmount()。问题是我想在操作调用之后立即访问道具,但是每当我运行console.log(this.props.note) 时,它都会打印未定义。那么如何在调用后访问 redux 状态呢?

我的行动:

export const fetchNoteDetail = (id, ) => async dispatch => {
    const response = await notes.get(`notes/${id}`)

    dispatch({type: 'FETCH_NOTE_DETAIL', payload: response.data})
}  

ComponentDidMount():

   componentDidMount() {
      const {id} = this.props.match.params
      this.props.fetchNoteDetail(id)

      console.log(this.props.note) //undefined

    }

【问题讨论】:

  • fetchNoteDetail 是异步的,所以它实际上在console.log 语句之后运行。 (但即使它是同步的,它也只会同步更新 Redux 存储 - 你的 React 组件只会在短时间内收到它的新 props 并重新渲染,在 componentDidMount 完成后再次渲染。)
  • 首先,如果获取的数据存储在 redux 存储中,这不是您在类组件中访问 redux 存储的方式,我假设您正在使用基于您提到的 compoentDidMount
  • 其次请添加你的redux store加reducer的代码
  • @RobinZigmond 所以我是否有任何可能的方法可以做到这一点?

标签: javascript reactjs redux


【解决方案1】:

componentDidUpdate() 中运行这个console.log

【讨论】:

    猜你喜欢
    • 2019-05-08
    • 2018-07-23
    • 2021-12-16
    • 2018-09-20
    • 2019-12-04
    • 2021-04-28
    • 2018-07-21
    • 2016-10-27
    • 1970-01-01
    相关资源
    最近更新 更多