使用 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
})
这样我得到了申请,但我认为这不是最好的方法。有什么建议吗?