React Redux操作未生效



当输入发生更改时,我正在尝试更改redux的存储。我对属性的更改有如下意见:

onChange= {(event, value) => {
if(value) {
addCountry(value)
console.log(countries)
}

countries(控制台日志中的一个(是我在发送addCountry及其值时希望更改的内容。

addCountry操作如下:

export function addCountry(name) {
return {type: 'ADD_COUNTRY', payload: name }
}

我的减速器是这样工作的:

const initialState = {
countries: ['World'],
};
function rootReducer(state = initialState, action) {

if(action.type === 'ADD_COUNTRY'){
return {
...state,
countries: [...state.countries, action.payload]
}
}
}
export default rootReducer;

我不明白,每次我改变输入,然后console.log(国家(,如前所示,它的控制台日志是一样的,就好像它是异步工作的,但我知道redux是同步工作的。

如果你担心我没有将我的组件连接到商店,因为我应该让我向你展示我做得对:

// MapStateToProps for access to specific items of the store-state
function mapStateToProps(state) {
return {
countries: state.countries,
};
}
// MapDispatchToProps to directly dispatch an action when called in this component
function mapDispatchToProps(dispatch) {
return {
addCountry: (name) => dispatch(addCountry(name)),
};
}
// Connects the Component with the store
export default connect(
mapStateToProps,
mapDispatchToProps
)(CountrySelect);

我试图显示一个包含国家信息的图表,如果国家没有改变,我的图表也没有,所以我需要解决这个问题。

但我知道redux是同步工作的。

有点。它没有使用promise,但仍然是React,这意味着countries在下一次渲染之前不会更新。

既然你使用钩子,你可能希望它看起来像:

useEffect(() => {
console.log(countries);
}, [countries]);

如果你仍然没有得到console.log,那么你需要弄清楚它在哪里失败了。我会做:

export function addCountry(name) {
console.log('ADD_COUNTRY payload created with ' + name);
return {type: 'ADD_COUNTRY', payload: name }
}
// MapDispatchToProps to directly dispatch an action when called in this component
function mapDispatchToProps(dispatch) {
return {
addCountry: (name) => {
console.log('addCountry dispatched');
dispatch(addCountry(name)),
}
}
}
function rootReducer(state = initialState, action) {
if(action.type === 'ADD_COUNTRY'){
console.log('ADD_COUNTRY state updating')
return {
...state,
countries: [...state.countries, action.payload]
}
}
}
onChange= {(event, value) => {
console.log('onChange called');
if(value) {
console.log('onChange if');
addCountry(value)
console.log(countries)
}
}

找出故障在哪里。

最新更新