我正在使用 React hooks 和 contextAPI 开发一个简单的 MERN stack todo 应用程序,我使用 axios 从 mongodb 数据库中获取数据,并设置 initialState 数组变量useEffect来模拟componentDidMount,然后将initialState作为参数传给useReducer。我的问题是子组件没有收到 initialState 而是一个空数组,但是所有其他 Prop (例如调度和加载变量)都可以通过。为什么 useReducer 返回空状态数组?
父组件:
import React, { useEffect, useState, useReducer } from 'react';
import Header from './components/header/Header';
import Main from './components/main/Main';
import AppContext from './context/AppContext';
import axios from 'axios';
import './stylesheets/index.scss';
function App() {
const [initialState, setInitialState] = useState([]);
const [isError, setIsError] = useState(false);
const [isLoading, setIsLoading] = useState(false);
/* Fetch data */
const fetchData = async () => {
setIsError(false);
setIsLoading(true);
try {
const response = await axios.get('/list');
setInitialState(response.data);
} catch (error) {
setIsError(true);
console.log(`Unable to get: ${error}`);
}
setIsLoading(false);
};
/* Post new data */
const postNewData = async (parameter) => {
setIsError(false);
try {
const response = await axios.post('/list', parameter);
console(response.data);
} catch (error) {
setIsError(true);
console.log(`Unable to post: ${error}`);
}
};
/* Delete data */
const deleteData = async (id) => {
setIsError(false);
try {
const response = await axios.delete(`/list/${id}`);
console(response.data);
} catch (error) {
setIsError(true);
console.log(`Unable to delete: ${error}`);
}
};
useEffect(() => {
/* On load fetch data from the database */
fetchData();
}, []);
useEffect(() => {
console.log(initialState);
}, [initialState]);
const appReducer = (state = initialState, action) => {
switch (action.type) {
case 'ADD_NEW_LIST':
return postNewData(action.new_list);
case 'DELETE_LIST':
return deleteData(action.list_id);
default:
return state;
}
};
const [state, dispatch] = useReducer(appReducer, initialState);
return (
<AppContext.Provider value={{ state, dispatch, isError, isLoading }}>
<div className='App'>
<Header />
<Main />
</div>
</AppContext.Provider>
);
}
export default App;
这是主组件内的子组件:
import React, { useContext, useEffect, useState } from 'react';
import AppContext from '../../context/AppContext';
function Listarea() {
const { state, isError, isLoading, dispatch } = useContext(AppContext);
console.log(state);
console.log(isError);
console.log(isLoading);
return <div className='list-area'>list area here</div>;
}
export default Listarea;
正如您所看到的,数据存在于父组件中,但子组件中不存在,除了能够进入的其他 Prop 之外。
最佳答案
如果你更新你的initialState值,它不会改变你的useReducer的状态。
您可以简单地使用一种状态并在获取数据时更新该状态,您不需要initialState 和state 两者,因此您可以删除initialState。
const appReducer = (state = initialState, action) => {
switch (action.type) {
case 'SET_DATA':
return action.data;
case 'ADD_NEW_LIST':
return postNewData(action.new_list);
case 'DELETE_LIST':
return deleteData(action.list_id);
default:
return state;
}
};
const [state, dispatch] = useReducer(appReducer, []);
const fetchData = async () => {
setIsError(false);
setIsLoading(true);
try {
const response = await axios.get('/list');
dispatch({ type: 'SET_DATA', data: response.data });
} catch (error) {
setIsError(true);
console.log(`Unable to get: ${error}`);
}
setIsLoading(false);
};
关于javascript - 当第一次在 useEffect 上获取数据时,为什么 React 的 useReducer 返回空状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61053418/