此问题在此处已有答案:
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
后,它是空的!
1条答案
按热度按时间velaa5lx1#
State的工作方式类似于快照,所以axios回调中的
data
是空的。因此,将news
设置为data也将是空的。因此,不要使用当前的实现,而是直接在jsx中使用data
。请记住,当通过reducer改变状态时,更新后的状态将只在下一次渲染时可用,这在你的案例中没有发生,因为你没有直接使用data
。如果你这样做了,如果useState
已经是一个状态,那么使用它也是多余的