【问题标题】:React Native Redux: Action dispatched, return resultsReact Native Redux:动作分派,返回结果
【发布时间】:2017-06-18 07:10:54
【问题描述】:

在 redux 中,当一个 action 被调度时,reducer 会相应地改变 state,调用该 action 的组件也可以访问 state(通过 props 由 Provider 传递)。我说的对吗?

状态是访问组件中操作结果的唯一方法吗? (调用动作的组件)。

如何将回调函数传递给操作,并使用它将结果发送回组件?

【问题讨论】:

    标签: reactjs react-native redux react-redux redux-thunk


    【解决方案1】:

    在redux中,当一个action被派发时,reducer会改变状态 因此,调用动作的组件也有 访问状态(通过 Provider 的 props 传递)。我说的对吗?

    是的,你是对的。调度动作时,您需要指定动作创建者,在动作创建者内部,您可以触发同步或异步动作(使用 thunk 或 saga),并且每个动作创建都有 actionType 和有效负载(可选。在动作创建者内部调用动作时,所有减速器将得到通知并匹配 action 传递的类型。

    状态是访问动作结果的唯一途径 零件? (调用动作的组件)。

    作为 redux 的最佳实践,状态应该由 reducer(作为纯函数)更改,如果您监听该状态,它会作为 props 传递给组件。

    如何将回调函数传递给动作,并使用它来 将结果发送回组件?

    您可以将回调函数传递给动作创建者,动作创建者只是一个函数。

    【讨论】:

      【解决方案2】:

      在 redux 中,当一个 action 被分发时,reducer 会相应地改变 state,调用该 action 的组件也可以访问 state(通过 props 由 Provider 传递)。我说的对吗?

      当一个动作在 redux 模式中被触发时,所有的 reducer 都会运行,但只有要作用于这种类型的 action 的 reducer 才会在 store 上执行 reduce 工作。有时你可以有一个不返回动作类型的动作。如果我希望减速器减少应用商店中的状态,我通常会返回一个动作对象,否则我不需要。请记住,当一个状态减少时,所有渲染它的值的组件都会重新渲染。

      状态是访问组件中操作结果的唯一方法吗? (调用动作的组件)。

      我认为您可以设计一个动作以在执行后返回结果,但您不会完全使用 redux 模式。

      如何将回调函数传递给操作,并使用它将结果发送回组件?

      我以前从未尝试过,但我认为 promise 是一个不错的选择。我总是使用axios 从服务器获取我的结果,如果我有结果,那么调度另一个 axios 让减速器更新状态,否则调度一个用于错误处理的减速器。

      //actions
      const axios from 'axios'
      const FETCH_ITEMS = 'FETCH_ITEMS'
      const FETCH_ITEMS_RECEIVED = 'FETCH_ITEMS_RECEIVED'
      const FETCH_ERROR = 'FETCH_ERROR'
      const SERVER_BASE_URL = 'localhost:4000/'
      
      export function itemsReceive(items){
         return {
            type: FETCH_ITEMS_RECEIVED,
            items
          }
      }
      
      export function itemsFetchError(){
         return {
            type: FETCH_ERROR,
            errorMsg: 'There was an issue fetching items.'
          }
      }
      
      //This function shall dispatch the two actions above in case we have the expected result or an error.
      export function fetchItems(){
          return dispatch => {
             axios.get(SERVER_BASE_URL  + 'items').
              then(function(res){
                 const { data } = res
                   if(data.status === 0){ //data.status is just a status sent by my server to show the response is good.
                     const items = data.response
                     dispatch(itemsReceive(items))
                   }else{
                     dispatch(itemsFetchError())
                   }
              }).catch(function(err)){//this error here is usually caused by network disruption
                    dispatch(itemsFetchError())
              }
          }
      }
      

      【讨论】:

      • 感谢您的详细解答。
      猜你喜欢
      • 2017-11-11
      • 1970-01-01
      • 2016-11-14
      • 1970-01-01
      • 2019-03-19
      • 1970-01-01
      • 1970-01-01
      • 2017-10-15
      • 2017-02-10
      相关资源
      最近更新 更多