首页 > 解决方案 > 在 componentDidMount 中调度一个动作,该动作接收一个 redux 道具作为有效负载

问题描述

使用 redux 道具触发 componentDidMount () 内部动作的最佳方法是什么?前任:

import { fetchUser } from '../actions'
    class Example extends Component {
          ComponentDidMount(){
            this.props.fetchUser(this.props.id)
          } ... 

mapDispatchToProps = dispatch => ({
   fetchUser: (payload) => dispatch(fetchUser(payload))
})

mapStateToProps = state => ({
 id: state.user.id
})

问题是 ComponentDidMount () 是在类甚至从商店接收道具之前安装的。这样我的 this.props.id 在方法中就是 = 'undefined' 。我发现的一种解决方案是按如下方式运行,但我不知道这是否是最好的方法:

    import { fetchUser } from '../actions'
        class Example extends Component {
     fetchUser = () => {
     this.props.fetchUser(this.props.id)
              }
render(){
  if(this.props.id !== undefined) this.fetchUser()
 } ...
}

    mapDispatchToProps = dispatch => ({
       fetchUser: (payload) => dispatch(fetchUser(payload))
    })

    mapStateToProps = state => ({
     id: state.user.id
    })

这样我得到了申请,但我认为这不是最好的方法。有什么建议吗?

标签: reactjsreduxaxios

解决方案


你必须了解 React 组件的生命周期。当组件被挂载时,它可以获取数据,但此时你的组件需要渲染一些东西。如果数据还没有被加载,你应该返回 null 来告诉 react 在那一点上它没有渲染任何东西,或者可能是一个加载指示器来表明它正在获取数据?

import { fetchUser } from '../actions'

class Example extends Component {
    componentDidMount() {
        this.props.fetchUser();
    }
    render(){
        const { loading, error, user } = this.props;

        if (loading) {
            return <LoadingIndicator />;
        }

        if (error) {
            return <div>Oh noes, we have an error: {error}</div>;
        }

        // Render your component normally
        return <div>{user.name}</div>;
    }
}

你的 reducer 应该默认将 loading 设置为 true,当你的 fetch 完成时,将 loading 设置为 false,并根据 fetch 是否失败/完成来设置用户或错误。


推荐阅读