我有这个动作:
export const connectToServer = (url, config, method) => {
return (dispatch) => {
dispatch({type: CONNECTION_START});
axios({
method: method,
url: url,
data: config
})
.then((response) => {
dispatch({type: CONNECTION_LOADING_SUCCESS, payload: response.data});
})
.catch((error) => {
dispatch({type: CONNECTION_LOADING_ERROR, payload: error.response.data});
})
}
};
和2个相同的减速器:
const initialState = {
data: null,
isLoading: false,
error: null
};
export const connectToServerReducer = (state = initialState, action) => {
switch (action.type) {
case CONNECTION_START :
return {...state, isLoading: true};
case CONNECTION_LOADING_SUCCESS :
return {...state, isLoading: false, data: action.payload, error: null};
case CONNECTION_LOADING_ERROR:
return {...state, isLoading: false, data: null, error: action.payload};
default :
return state
}
};
export const differentUrlConnectToServerReducerTest = (state = initialState, action) => {
switch (action.type) {
case CONNECTION_START :
return {...state, isLoading: true};
case CONNECTION_LOADING_SUCCESS :
return {...state, isLoading: false, data: action.payload, error: null};
case CONNECTION_LOADING_ERROR:
return {...state, isLoading: false, data: null, error: action.payload};
default :
return state
}
};
我的商店看起来是这样的:
const rootReducer = combineReducers({
allUsersData: connectToServerReducer,
testData: differentUrlConnectToServerReducerTest
});
const configureStore = () => createStore(rootReducer, applyMiddleware(thunk));
export default configureStore
然后我使用reduxhook在我的组件中获得一个带有数据的状态
const allUsersData = useSelector(state => state.allUsersData);
const testData = useSelector(state => state.testData);
const dispatch = useDispatch();
最后我派他们
dispatch(connectToServer(`${BASE_URL}user/allUsersWithPets`, null, 'get'));
dispatch(connectToServer(`${BASE_URL}fakeUrl`, null, 'get'));
我在allUsersData
中接收到正确的数据,但我也在testData
中接收到它,但我应该在testData
中接收到初始状态(空对象(,因为url是假的
我哪里错了?
您需要分离减速器,使用不同的初始状态,例如:
connectToServer.js
connectToServerTest.js
或者,您可以尝试将测试对象添加到connectToServerReducer的初始状态。(但不是一个好的解决方案(
const initialState = {
data: null,
testData: null,
isLoading: false,
error: null
};
请记住,数组情感不会分配值,而是分配地址,因此";数据";数组在connectToServerReducer和connectToServerReducerTest中都是相同的数组。
第二个问题是,您在两个减速器中调用相同的操作名称,这导致它们不仅共享我告诉您的上一个问题中的相同变量,而且还共享分配给它们的相同值。只需将其更改为:
CONNECTION_TEST_LOADING_SUCCESS
CONNECTION_TEST_LOADING_ERROR
CONNECTION_TEST_START
PS:而不是使用:
export const connectToServer = (url, config, method) => {
return (dispatch) => {
...
}
}
用途:
export const connectToServer = (url, config, method) => (dispatch) => {
...
}