React Native Redux:已调度操作,return 结果

React Native Redux: Action dispatched, return results

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

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

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

In redux, when an action is dispatched, reducer will change the state accordingly, the component which have called the action, also have access to the state ( passed through props by Provider ). Am I right?

当在 redux 模式中触发一个动作时,所有的 reducer 运行,但只有对这种类型的动作起作用的 reducer 才会在 store 上做减少工作。有时您可以执行不属于 return 操作类型的操作。如果我想让 reducer 减少应用程序商店中的状态,我通常 return 一个动作对象,否则我不需要。请记住,当一个状态被减少时,所有渲染它的值的组件都是 re-rendered.

is the state the only way to access results of the action in the component? ( the component which have called the action ).

我认为你可以设计一个动作来 return 它在执行后产生结果,但你不会完全使用 redux 模式。

How about passing a callback function to the action, and using that to send the result back to the component?

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

//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())
        }
    }
}

In redux, when an action is dispatched, reducer will change the state accordingly, the component which have called the action, also have access to the state ( passed through props by Provider ). Am I right?

是的,你是对的。调度动作时,您需要指定动作创建者,在动作创建者内部,您可以触发同步或异步动作(使用 thunk 或 saga),并且每个动作创建都有 actionType 和 payload(可选。在动作创建者内部调用动作时,所有 reducer将获取通知并匹配操作传递的类型。

is the state the only way to access results of the action in the component? ( the component which have called the action ).

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

How about passing a callback function to the action, and using that to send the result back to the component?

你可以将回调函数传递给action creator,action creator只是一个函数。