Redux-从不同文件使用相同功能更新存储

Redux-从不同文件使用相同功能更新存储,redux,react-redux,Redux,React Redux,作为react.js+redux的新手,我面临以下难题: 我有多个文件,需要根据存储的当前状态以完全相同的方式更新存储。目前,我只是简单地复制粘贴相同的代码(以及所需的mapStateToProps),这会再次变干 与下面类似,其中getData是一个Ajax调用,位于actions文件中,props.timeAttribute来自mapStateToProps: props.getData(props.timeAttribute).then((newState) => { con

作为react.js+redux的新手,我面临以下难题:

我有多个文件,需要根据存储的当前状态以完全相同的方式更新存储。目前,我只是简单地复制粘贴相同的代码(以及所需的mapStateToProps),这会再次变干

与下面类似,其中getData是一个Ajax调用,位于actions文件中,props.timeAttribute来自mapStateToProps:

props.getData(props.timeAttribute).then((newState) => {
    console.log(newState)
})
这样的函数会出现在actions文件中吗?可以从该操作文件中读取当前状态吗?或者人们通常会创建某种helperFile.js,其中存在类似的函数,并从其他文件中调用该函数


谢谢

如果您的文件正在执行相同的操作,那么是的,您可以将操作创建者放在一个单独的文件中并将其导出。理论上,可以通过将状态作为参数传递来将状态放入操作中,但操作背后的原理是,它向应用程序宣布发生了什么(由操作函数返回值上的
type
属性表示)。负责处理
类型
的减速器功能随后更新状态

您可以访问action creator中存储的当前状态,如下所示:

export const testAction = (someParam) => {
  return (dispatch, getState) => {
    const {
     someState,
    } = getState(); //getState gets the entire state of your application

   //do something with someState and then run the dispatch function like this: 
   dispatch(() => {type: ACTION_TYPE, payload: updatedState})




}
我喜欢这种方法,因为它将访问状态的所有逻辑封装在需要访问它的一个函数中


但不要修改动作创建者内部的状态!这应该是只读的。应用程序的状态只能通过reducer函数更新

如果您的文件正在执行相同的操作,那么是的,您可以将操作创建者放在一个单独的文件中并将其导出。理论上,可以通过将状态作为参数传递来将状态放入操作中,但操作背后的原理是,它向应用程序宣布发生了什么(由操作函数返回值上的
type
属性表示)。负责处理
类型
的减速器功能随后更新状态

您可以访问action creator中存储的当前状态,如下所示:

export const testAction = (someParam) => {
  return (dispatch, getState) => {
    const {
     someState,
    } = getState(); //getState gets the entire state of your application

   //do something with someState and then run the dispatch function like this: 
   dispatch(() => {type: ACTION_TYPE, payload: updatedState})




}
我喜欢这种方法,因为它将访问状态的所有逻辑封装在需要访问它的一个函数中


但不要修改动作创建者内部的状态!这应该是只读的。应用程序的状态只能通过reducer函数更新

是的,建议为您的操作维护一个单独的文件。 下面是我如何使用操作获取信息和发送操作的示例

export const fetchComments = () => (dispatch) => {
    console.log("Fetch Comment invoked");
    /*you can use your Ajax getData call instead of fetch.
    Can also add parameters if you need */
    return fetch(baseUrl + 'comments')
        .then(response => {
            if (response.ok){
                return response;
            }
            else {
                var error = new Error('Error ' + response.status + ': ' + response.statusText);
                error.response = response;
                throw error;
            }
        },
        error => {
            var errmess = new Error(error.message);
            throw errmess;
        })
        .then(response => response.json())
        .then(comments => dispatch(addComments(comments)))
        .catch(error => dispatch(commentsFailed(error.message)));
}
/* Maintain a separate file called ActionTypes.js where you can store all the ActionTypes as Strings. */
export const addComments = (comments) => ({
    type : ActionTypes.ADD_COMMENTS,
    payload : comments
});

export const comments = (errMess) => ({
    type : ActionTypes.COMMENTS_FAILED,
    payload : errMess
});
一旦收到分派操作,您就需要一个减速机来捕获该操作并对存储进行更改。 请注意,此减速器必须是纯函数

export const comments = (state = { errMess: null, comments:[]}, action) => {
  console.log("inside comments");
  switch (action.type) {
    case ActionTypes.ADD_COMMENTS:
      return {...state, errMess: null, comments: action.payload};

    case ActionTypes.COMMENTS_FAILED:
      return {...state, errMess: action.payload};

    default:
      return state;
  }
};
不要忘记在configureStore()中组合减速器

在使用动作的组件中,使用

const mapDispatchToProps = dispatch => ({
    fetchComments : () => dispatch(fetchComments()),
})
注意:将组件导出为

export default connect(mapStateToProps,mapDispatchToProps)(Component);

是的,建议为您的操作维护一个单独的文件。 下面是我如何使用操作获取信息和发送操作的示例

export const fetchComments = () => (dispatch) => {
    console.log("Fetch Comment invoked");
    /*you can use your Ajax getData call instead of fetch.
    Can also add parameters if you need */
    return fetch(baseUrl + 'comments')
        .then(response => {
            if (response.ok){
                return response;
            }
            else {
                var error = new Error('Error ' + response.status + ': ' + response.statusText);
                error.response = response;
                throw error;
            }
        },
        error => {
            var errmess = new Error(error.message);
            throw errmess;
        })
        .then(response => response.json())
        .then(comments => dispatch(addComments(comments)))
        .catch(error => dispatch(commentsFailed(error.message)));
}
/* Maintain a separate file called ActionTypes.js where you can store all the ActionTypes as Strings. */
export const addComments = (comments) => ({
    type : ActionTypes.ADD_COMMENTS,
    payload : comments
});

export const comments = (errMess) => ({
    type : ActionTypes.COMMENTS_FAILED,
    payload : errMess
});
一旦收到分派操作,您就需要一个减速机来捕获该操作并对存储进行更改。 请注意,此减速器必须是纯函数

export const comments = (state = { errMess: null, comments:[]}, action) => {
  console.log("inside comments");
  switch (action.type) {
    case ActionTypes.ADD_COMMENTS:
      return {...state, errMess: null, comments: action.payload};

    case ActionTypes.COMMENTS_FAILED:
      return {...state, errMess: action.payload};

    default:
      return state;
  }
};
不要忘记在configureStore()中组合减速器

在使用动作的组件中,使用

const mapDispatchToProps = dispatch => ({
    fetchComments : () => dispatch(fetchComments()),
})
注意:将组件导出为

export default connect(mapStateToProps,mapDispatchToProps)(Component);

是否分派操作并使用mapDispatchToProps?是否分派操作并使用mapDispatchToProps?