【发布时间】:2019-11-23 13:08:50
【问题描述】:
在 redux 中,我们使用动作来处理 crud 操作。但我在某些点上卡住了。如果我们在组件内部发送异步请求。我们可以轻松应对。但是当我们通过动作发送请求时,我们不知道发生了什么。请求发送成功了吗?花了多少时间?返回什么样的响应?我们不知道
我会用样本澄清问题..
让我们更新一个帖子。
onClick () {
postsApi.post(this.state.post) | we know how much time
.then(res => res.data) | has took to execute
.then(res => { | request
console.log(res) // we have the response
})
.catch(err => console.log(error))
}
但是如果我们使用动作
onClick () {
this.props.updatePost(this.state.post) // we know nothing what will happen
}
或处理传入的道具。假设我有 fetchPost() 操作来检索帖子
componentDidMount(){
this.props.fetchPost()
}
render 方法和 componentDidUpdate 也将运行。这个很酷。但是如果我想通过传入的 props 来更新我的状态呢?我无法在 componentDidUpdate 方法中执行此操作。它会导致无限循环。
如果我使用 componentWillUpdate 方法,那么一切正常,但我收到了这个警告。
警告:componentWillReceiveProps 已被重命名,而不是 推荐使用。将数据获取代码或副作用移动到 组件更新。如果您在道具更改时更新状态, 重构您的代码以使用记忆技术或将其移动到静态 getDerivedStateFromProps
我不能将componentDidUpdate 方法用于无限循环。既不是getDerivedStateFromProps 方法,因为它每次状态变化时都会运行。
我应该继续使用componentWillMethod 吗?否则我应该使用什么以及为什么(为什么componentWillMethod 不安全?)
【问题讨论】:
-
如果我们使用 redux 操作,为什么我们无法理解发生了什么?您将使用一些成功或错误信息更新正在运行的商店,然后您将能够在连接的组件中访问这些值。请向我们展示您的操作代码。
标签: javascript reactjs redux