使用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
})
这样我得到了申请,但我不认为这是最好的方式 . 有什么建议吗?
2 回答
你尝试过使用async / await吗?
您必须了解反应组件的生命周期 . 组件安装后,它可以获取数据,但此时您的组件需要呈现一些内容 . 如果尚未加载数据,您应该返回null以告知它在该点没有呈现任何内容,或者可能是一个加载指示器以显示它正在获取数据?
您的reducer默认情况下应该将加载设置为true,并且当您的提取完成时,将加载设置为false,并根据提取是否失败/完成来设置用户或错误 .