简体   繁体   English

如何在React Redux中获得状态的先前值

[英]How to get the previous value of state in React Redux

I have this reducer 我有这个reducer

import { FETCH_WEATHER } from "../actions/index";

export default function(state = [], action) {
  switch (action.type) {
    case FETCH_WEATHER:
      console.log(state)
      return [action.payload.data,...state];
    default:
      return state
  }
}

but whenever I console.log the state the result is always undefined 但是每当我console.log state ,结果始终是undefined

and here is my action 这是我的action

import axios from 'axios';

const API_KEY = '...';
const ROOT_URL = `...`
export const FETCH_WEATHER = 'FETCH_WEATHER';

export function fetchWeather(city){
  const url = `${ROOT_URL}&q=${city},us`;
  const request = axios.get(url)
  return {
    type : FETCH_WEATHER,
    payload: request,
  }
}

I'm thinking to create a constant to hold the data overall and just pass it in reducer but I don't think it's the right approach. 我正在考虑创建一个常量以保存整个数据,然后将其传递给reducer,但我认为这不是正确的方法。

Question: How can I access the previous state in the reducer so that whenever I console.log there is a value. 问题:如何访问化console.log器中的先前状态,以便每当我console.log存在一个值。

Here is the code codesandbox 这是代码codeandbox

Previous state is stored in your state variable, as defined in your reducer. 先前状态存储在您的化简器中定义的state变量中。 Previous state can therefore be accessed in your reducer via the state variable. 因此,可以通过state变量在化简器中访问先前状态。

It looks like you have a block syntax error that may be causing you problems (see correction below). 看来您有一个区块语法错误可能会导致您遇到问题(请参见下面的更正)。

Also, if you want to log previous state to the console when ever your reducer is run, consider placing the call to console.log at the beginning of your reducer: 另外,如果要在运行reduce时将以前的状态记录到控制台,请考虑将对console.log的调用放在reduce的开头:

import { FETCH_WEATHER } from "../actions/index";

export default function(state = [], action) {

  // console.log(state) // Add this to log previous state for every call to reducer

  switch (action.type) {

    case FETCH_WEATHER: { // Added { here

      console.log(state)
      return [action.payload.data,...state];

    } // Added } here

    default:
      return state
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM