【问题标题】:Best practise to handle with responses and incoming props处理响应和传入道具的最佳实践
【发布时间】: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


【解决方案1】:

如果我理解正确,您想做的是安全地更改您的本地状态仅当您的例如updatePost 成功。

如果确实是你的情况,你可以在你的updatePost 上传递一个回调函数,只要你的更新成功就调用它。

successfulUpdate() {
 // do your thing
   this.setState( ... );
}
onClick () {
   this.props.updatePost(this.state.post, this.successfulUpdate)  // we know nothing what will happen
}

更新:

您还可以记住,如果您的操作返回 promise,那么您可以只使用 then 方法:

onClick () {
   this.props.updatePost(this.state.post).then(this.onFulfilled, this.onRejected)
}

【讨论】:

    【解决方案2】:

    我认为在这种情况下我们可以使用 redux-thunk。如果我们调度一个异步函数而不是调度一个动作对象呢?

    【讨论】:

      【解决方案3】:

      “getDerivedStateFromProps 方法都不行,因为它在每次状态变化时都会运行。” - 这有关系吗?您可以通过在内部使用一个简单的条件来避免在每个 getDerivedStateFromProps 调用中设置状态。

      例子:

      static getDerivedStateFromProps(props, state) {
         if (props.post !== state.post) { // or anything else
           return {
              post: props.post,
           };
         }
      
         return null;
      };
      

      不会发生无限循环。

      【讨论】:

        【解决方案4】:

        这是我处理这种情况的方法。我们可以对 api 调用等异步调用进行 redux-thunk。如果我们定义返回 promise 的动作会怎样?请检查下面的代码。

        actions.js
        
        export const GetTodoList = dispatch => {
          return Axios.get('SOME_URL').then(res => {
            // dispatch some actions
            
            // return result
            return res.data;
          });
        }
        
        TodoList.js
        
        onClick = async () => {
          const { GetTodoList } = this.props;
          try {
            const data = await GetTodoList();
            // handler for success
            this.setState({
              success: true,
              data
            });
          } catch {
            // handler for failure
            this.setState({
              success: fail,
              data: null
            });
          }
            
        }
        
        const mapStateToProps = state => ({
          GetTodoList
        });

        因此,感谢 redux-thunk,我们可以使用 API(返回 Promise)之类的操作。 让我知道你的意见。

        【讨论】:

          猜你喜欢
          • 2021-03-06
          • 1970-01-01
          • 2021-03-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-08-25
          • 1970-01-01
          相关资源
          最近更新 更多