reactjs - 在 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
})
这样我得到了申请,但我认为这不是最好的方法。有什么建议吗?
解决方案
你必须了解 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 是否失败/完成来设置用户或错误。
推荐阅读
- python - pands.read_json dtype 对象到整数/数字
- linux - 列表文件中的格式错误的条目 1
- laravel - 您可能需要一个额外的加载器来处理这些加载器的结果
- biopython - 如何从 FASTA 文件中进行多个成对对齐并打印相似度百分比?
- python - python中的.xlsx下载问题
- python - 如何根据另一个重复值将字符串从一行附加到另一行
- java - 如何使用 java KeyStroke 暂时关闭自动重复
- python - 我是 python 新手,这就是问题所在;\
- git - 当我 git stash 然后 git stash pop 我的更改总是未暂存
- arrays - CategoryComponent.html:53 ERROR 错误:尝试区分“[object Object]”时出错。只允许使用数组和可迭代对象