axios 我不能在redux reducer中改变我的当前状态,即使在分派了一个动作并将我需要的确切有效载荷传递给状态之后,

a14dhokn  于 5个月前  发布在  iOS
关注(0)|答案(1)|浏览(49)

此问题在此处已有答案

The useState set method is not reflecting a change immediately(19个回答)
上个月关门了。
这是在我的reducer.js中

export const initialState = {
  data: [],
};

const reducer = (state, action) => {
  console.log(action, "ACTIOn");
  switch (action.type) {
    case "FETCH_NEWS":
      return {
        ...state,
        data: action.payload,
      };
    default:
      return state;
  }
};

export default reducer;

字符串
这是我的News.js

import React, { useState, useEffect } from "react";
import { useStateValue } from "../StateProvider";
import axios from "axios";

function News() {
  const [{ data }, dispatch] = useStateValue();
  const [news, setNews] = useState([]);

  useEffect(() => {
    axios.get("https://jsonplaceholder.typicode.com/todos").then((res) => {
      console.log(res.data);
      dispatch({
        type: "FETCH_NEWS",
        payload: res.data,
      });
      setNews(data);
      console.log(news, "NUAKJSDAILSGDL");
    });
  }, []);

  return (
    <div className="App">
      <div className="App-header">
        <h1>{news}</h1>
      </div>
    </div>
  );
}

export default News;


My StateProvider.js

import React, { createContext, useContext, useReducer } from "react";

//Prepare the dataLayer
export const StateContext = createContext();

// Wrap our app and provide the Data Layer to every component
export const StateProvider = ({ reducer, initialState, children }) => (
  <StateContext.Provider value={useReducer(reducer, initialState)}>
    {children}
  </StateContext.Provider>
);

// Pull Information from the Data Layer
export const useStateValue = () => useContext(StateContext);


console.log给了我正确的操作顺序,也就是FETCH_NEWS和一个对象数组。当我试图将数据设置为操作有效载荷时,数据没有更新,当我尝试使用react hook用存储中的数据更新我的news后,它是空的!

velaa5lx

velaa5lx1#

State的工作方式类似于快照,所以axios回调中的data是空的。因此,将news设置为data也将是空的。因此,不要使用当前的实现,而是直接在jsx中使用data。请记住,当通过reducer改变状态时,更新后的状态将只在下一次渲染时可用,这在你的案例中没有发生,因为你没有直接使用data。如果你这样做了,如果useState已经是一个状态,那么使用它也是多余的

相关问题