redux mapDispatchToProps未更新状态



我是redux的新手,遇到了mapDispatchToProps的问题,我的react应用程序中有一个具有不同div的组件,每次用户单击div时,它都应该通过一个参数来更改所选颜色,然后将其作为道具再次传递。

我正在从初始状态获取道具,但无法使mapDispatchToProps正常工作。似乎有不同的方法来处理mapDispatchToProps,我已经尝试了一些,但都不起作用,这是我目前的情况,没有出现错误,但仍然无法正常工作

组件:

import React from 'react';
import { connect } from 'react-redux';
import { changeSelectedColor } from '../actions/actions';
const ColorPalette = ({ selectedColor, changeSelectedColor }) => {
return(
<div>
<div className='flex justify-center mb-2'>
<p>Selected color: {selectedColor}</p>
</div>
<div className='flex justify-center mb-2'>
<button onClick={() => changeSelectedColor('test')} className='border border-black'>
click to change
</button>
</div>
</div>
)
}
const mapStateToProps = (state) => {
return { 
selectedColor: state.colorReducer.selectedColor, 
}
}
const mapDispatchToProps = (dispatch) => {
return {
changeSelectedColor: (color) => dispatch(changeSelectedColor(color))    
}
}
export default connect(mapStateToProps, mapDispatchToProps)(ColorPalette);

减速器:

import { combineReducers } from "redux";
const initialState = {
selectedColor: 'black',
};
const colorReducer = (state = initialState, action) => {
switch(action.payload) {
case 'SET_SELECTED_COLOR':
console.log('changing color to ', action)
return {...state, selectedColor: action.payload};
default:
return state;
}       
}
export default combineReducers({
colorReducer,
});

动作:

export const changeSelectedColor = (color) => {
return {
type: 'SET_SELECTED_COLOR',
payload: color
}
}

我还尝试将mapDispatchToProps作为对象传递,在这种情况下,如果我理解正确,每个函数都应该自动用dispatch包装?并且不传递第二个参数来连接,并将dispatch作为道具,直接在点击时调度动作,但就像我说的两种方法都失败了

问题来自您的减速器:

const colorReducer = (state = initialState, action) => {
switch(action.type) { // <== here should be type not payload
case 'SET_SELECTED_COLOR':
console.log('changing color to ', action)
return {...state, selectedColor: action.payload};
default:
return state;
}       
}

建议(与答案无关(

把你的连接函数写如下:

const mapStateToProps = ({ colorReducer: { selectedColor } = {} }) => ({ 
selectedColor, 
});
const mapDispatchToProps = dispatch => ({
changeSelectedColor: color => dispatch(changeSelectedColor(color)),
});

还有你的行动和减速器:

export const changeSelectedColor = payload => ({
type: 'SET_SELECTED_COLOR',
payload,
});
const colorReducer = (state = initialState, { type, payload }) => {
switch (type) {
case 'SET_SELECTED_COLOR':
return { ...state, selectedColor: payload };
default:
return state;
}
};

在ReactJS中使用重组赋值,它非常常见,使您的代码更可读,更易于调试。

相关内容

  • 没有找到相关文章

最新更新