gpt4 book ai didi

javascript - redux mapDispatchToProps 不更新状态

转载 作者:行者123 更新时间:2023-12-04 10:12:02 27 4
gpt4 key购买 nike

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

我正在从初始状态获取 Prop ,但无法让 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);

reducer :
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 自动包装?并且不传递第二个参数来连接并将调度作为 Prop ,直接在点击时调度 Action ,
但就像我说的两种方法都失败了

最佳答案

问题来自您的 reducer :

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)),
});

还有你的 Action 和 reducer :

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 中使用重组赋值,它是如此普遍,使您的代码更具可读性和更好的调试。

关于javascript - redux mapDispatchToProps 不更新状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61290525/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com