React Redux中未更新InitialState



我正在尝试免疫地更改状态并返回一个新状态,但在UI组件中,新状态没有更改。已成功获取新的状态值,但未显示。我不明白背后的问题是什么。

任何人都有建议分享我

这是我的减速器:

import * as actionTypes from './actions';
const initialState = {
data: [
{id: 1, name: "accordion1", content: () => {}, status: 1},
{id: 2, name: "accordion2", content: () => {}, status: 0},
{id: 3, name: "accordion3", content: () => {}, status: 0},
]
}
const reducer = (state = initialState, action) => {
debugger;
switch(action.type) {
case actionTypes.ACTIVE_STATE:
debugger;
var newData = state.data;
for(var i= 0; i<newData.length; i++) {
newData[i].status = newData[i].status === 1 ? 0 : 1

}
return {
...state,
data: newData
}
default: 
return state; 
}
}
export default reducer;

这是我的UI组件没有更新:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actionTypes from '../store/actions';
class Accordion extends Component {
render() {
debugger;
return (
<div>
{this.props.accordions.map((accordion, index) => {
return (
<div key={index}>
<div>{accordion.status}</div>
<div className={`accordion ${accordion.status}`} onClick={this.props.expandAccordion}>
{accordion.name}
</div>
<div className="panel">
</div>
</div>
);
})}
</div>
);
}
}
const mapStateToProps = (state) => {
return {
accordions: state.data
};
}
const mapDispatchToProps = (dispatch) => {
return {
expandAccordion: () => dispatch({type: actionTypes.ACTIVE_STATE})
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Accordion);

我认为问题出在以下几行:

var newData = state.data;
for(var i= 0; i<newData.length; i++) {
newData[i].status = newData[i].status === 1 ? 0 : 1             
}

为什么?因为基本上,当你分配var newData = state.data;时,你实际上复制了对象引用,这样,你就不会让它保持不变,而且就React而言,它进行了肤浅的比较,它从未改变。

一个可能的解决方案是将此代码更改为不可变的更新:

const newData = state.data.map((entry) => ({...entry, status: entry.status === 1 ? 0 : 1}));
return {
...state,
data: newData
}

p.S:如果你想得到漂亮的裤子,你可以使用XOR来更新你的状态:({...entry, status: entry.status ^ 1})

您实际上正在改变状态。试试这个。。。

import * as actionTypes from './actions';

const initialState = {
data: [
{id: 1, name: "accordion1", content: () => {}, status: 1},
{id: 2, name: "accordion2", content: () => {}, status: 0},
{id: 3, name: "accordion3", content: () => {}, status: 0},
]
}
const reducer = (state = initialState, action) => {
switch(action.type) {
case actionTypes.ACTIVE_STATE:
return {
...state,
data: state.data.map((acdnObj) => {
return {
...acdnObj,
status: acdnObj.status === 1 ? 0 : 1,
}
}),
}
default: 
return state; 
}
}
export default reducer;

相关内容

  • 没有找到相关文章

最新更新