导航到其他状态后,我无法获得更新状态。我想使用在reducer中初始化并通过操作更新的dataState。在屏幕1上调度后,我使用了此状态,但是当我导航到另一个屏幕时,它返回未定义的状态。
store.js
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import reducers from './reducers.js';
export default createStore(reducers, applyMiddleware(thunk));
action.js
export const DATA_AVAILABLE = 'DATA_AVAILABLE';
export const addData = (data) => ({
type: DATA_AVAILABLE,
data
});
reducers.js
import { combineReducers } from 'redux';
import { DATA_AVAILABLE } from "./actions"
let dataState = { data: [] };
const dataReducer = (state = dataState, action) => {
switch (action.type) {
case DATA_AVAILABLE:
return {...state, data: action.data};
default:
return state;
}
};
const rootReducer = combineReducers({
dataReducer
})
export default rootReducer;
HomeScreen.js的用法
const dataReducer = useSelector(state => state.dataReducer);
const { data } = dataReducer;
useEffect(() => getData(), []);
const getData = () => {
setIsFetching(true);
let url =
"https://my-json-server.typicode.com/mesandigital/demo/instructions";
axios
.get(url)
.then(res => res.data)
.then(data => dispatch(addData(data)))
.catch(error => alert(error.message))
.finally(() => setIsFetching(false));
};
可以使用数据常量访问获取的数据。因此,这意味着dataState的状态在获取后会更新。但是,当我导航到其他屏幕并尝试访问dataState时,它将返回undefined。 我正在该屏幕上访问商店状态:
const dataReducer = useSelector(state => state.dataReducer);
const { data } = dataReducer;
数据常量返回未定义。我想念什么吗?
答案 0 :(得分:0)
好的,我在代码中发现了问题。我在useSelector之后设置了恒定值。 我直接调用useSelector常量,它起作用了。问题是当我调用它时没有设置另一个常量。还是谢谢你