分派操作后 Redux 状态未更新 [英] Redux state not being updated after dispatched actions

查看:22
本文介绍了分派操作后 Redux 状态未更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在调度操作后,我的 redux 状态没有正确更新.我正在使用 reduxredux-thunk 调用 API 并将其保存到 redux 存储中.我的状态应该保存一个 JSON 文件,因为将使用大量 JSON 文件,而且似乎没有任何 JSON 文件被存储到商店中.问题在底部说明

My redux state is not being properly updated after actions are dispatched. I am using redux and redux-thunk to make calls to an API and save it into a redux store. My state is supposed to hold a JSON file due to the fact that a lot of the JSON file will be used and it seems that none of the JSON file is being stored into the store. The problem is explained down at the bottom

这是我定义动作类型的types.js文件:

This is my types.js file that define the action types:

export const FETCHING_REQUEST = "FETCHING_REQUEST";
export const FETCHING_SUCCESS = "FETCHING_SUCCESS";
export const FETCHING_FAILURE = "FETCHING_FAILURE";

下一个文件是我的 appActions.js 文件,其中包含应用程序的某些操作.代码中的注释来自一个我从未删除过的不同的 stackoverflow 问题.

The next file is my appActions.js file that hold the certain actions of the app. The comments in the code are from a different stackoverflow question that i never deleted.

import { FETCHING_SUCCESS, FETCHING_REQUEST, FETCHING_FAILURE } from "./types";

// Actions for the redux store

export const fetchingRequest = () => {
  return {
    type: FETCHING_REQUEST
  };
};

export const fetchingSuccess = json => {
  return {
    type: FETCHING_SUCCESS,
    payload: json
  };
};

export const fetchingFailure = error => {
  return {
    type: FETCHING_FAILURE,
    payload: error
  };
};

// Function will not work in a component
// Maybe the issue is redux
// more likely to be the Fetch not working in this function
export const fetchData = url => {
  console.log("Should enter async dispatch");
  return async dispatch => {
    dispatch(fetchingRequest());
    try{
      let response = await fetch(url);
      let json = await response.json();
      let dispatchChecker = dispatch(fetchingSuccess(json));
      console.log("JSON",json);
      //console.log(JSON.stringify(json, null, 2));
    }catch(error){
      console.log("ERROR",error);
      dispatch(fetchingFailure(error));
    }
  };
};

在应用的组件中调用时,只调用fetchData.

When being called in components of the app, only fetchData shall be called.

appReducer.js 文件

appReducer.js file

import {
  FETCHING_SUCCESS,
  FETCHING_REQUEST,
  FETCHING_FAILURE
} from "../actions/types";
import * as data from "./../../../../pickerdata.json"; // for debugging issues
import * as sample from "../../../../sampledata.json";
const initialState = {
  isFetching: false,
  errorMessage: "",
  articles: null
};

const appReducer = (state = initialState, action) => {
  switch (action.types) {
    case FETCHING_REQUEST:
      console.log("request from reducer");
      return { ...state, isFetching: true };
    case FETCHING_FAILURE:
      console.log("failure from reducer");
      return { ...state, isFetching: false, errorMessage: action.payload };
    case FETCHING_SUCCESS:
      console.log("success from reducer");
      return { ...state, isFetching: false, articles: action.payload };
    default:
      return state;
  }
};

export default appReducer;

创建商店的index.js

index.js where the store is created

import { AppRegistry } from "react-native";
import App from "./App";
import { name as appName } from "./app.json";
import { Provider } from "react-redux";
import React, { Components } from "react";
import { createStore, applyMiddleware } from "redux";
import appReducer from "./src/data/redux/reducers/appReducer";
import thunk from "redux-thunk";

const store = createStore(appReducer, applyMiddleware(thunk));

store.subscribe(()=> {
  console.log("State Updated", store.getState());
})

console.log("Store", store.getState());
const AppContainer = () => (
  <Provider store={store}>
    <App />
  </Provider>
);

AppRegistry.registerComponent(appName, () => AppContainer);

这是将我的商店连接到组件的代码

This is the code to connect my store to components

    const mapStateToProps = state => {
      return { response: state };
    };

    const mapStateToDispatch = dispatch => ({
      fetchData: url => dispatch(fetchData(url))
    });

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

这里的问题是 redux 状态没有被更新.使用控制台,我知道对 API 的 fetch 调用正在工作,因为 JSON 文件将显示在控制台中.使用 store.subscribestore.getState,我可以看到 store 没有改变,并且它与 appReducer.js 文件.

The problem here is that the redux state is not being updated. Using the console, I know that the fetch call to the API is working because the JSON file will be shown in the console. Using store.subscribe and store.getState, I am able to see that the store does not change and that it stays the same as the the initial state described in the appReducer.js file.

例如在 appActions.js 文件中的 fetchData 方法中.第一个调度是 fetchingRequest 并且 redux 存储应该看起来像这样

for instance in the fetchData method in the appActions.js file. The first dispatch is to fetchingRequest and the redux store should look like this

{isFetching: true, errorMessage: "", articles: null }

反而是这样

{isFetching: false, errorMessage: "", 文章: null }

获取 API 成功后的下一个分派是 fetchingSuccess 操作,redux 存储应如下所示

and the next dispatch after the fetch to the API is successful is the fetchingSuccess action and the redux store should look like this

{isFetching: false, errorMessage: "", 文章: JSONfile }

但看起来像这样

{isFetching: false, errorMessage: "", 文章: null }

推荐答案

在你的 types.js 文件中:

创建一个新类型 FETCHING_STATUS(例如)

Create a new type FETCHING_STATUS (for example)

在您的 fetchData 函数中:

replace dispatch(fetchingRequest());通过

dispatch({type: FETCHING_STATUS, payload: { isFetching: true }});

dispatch(fetchingSuccess());替换为

dispatch({type: FETCHING_STATUS, payload: {isFetching: false, articles: fetchingSuccess()}});

dispatch(fetchingFailed()); 替换为

dispatch({type: FETCHING_STATUS, payload:  {isFetching: false, errorMessage: fetchingFailed()}});

在您的 appReducer.js 中:

import { combineReducers } from "redux";

function fetchingStatusReducer(state = {}, action) {
  switch (action.type) {
    case FETCHING_STATUS:
      return action.payload;
    default:
      return state;
  }
}

export default combineReducers({
  fetchingStatus: fetchingStatusReducer
});

然后 store.getState().fetchingStatus 将根据需要更新

Then store.getState().fetchingStatus will get updated as you want

这篇关于分派操作后 Redux 状态未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆