我在Redux中有一个操作,它可以删除3个条目的硬编码数组中的最后一个项。
它工作得很好,但是我有第二个属性(dataLength)来计算数组的长度。在分派操作时,我希望从数组中移除最后一项,同时同时更新数组长度。
正在发生的事情是,项目被移除数组,但长度(dataLength)直到我再次分派操作时才会更新。
所以我有两个问题:
谢谢
减速器
const initialState = {
data: [
{
id: 0,
title: 'title 1'
},
{
id: 1,
title: 'title 2'
},
{
id: 2,
title: 'title 3'
}
],
dataLength: null
}
const data = (state = initialState, action) => {
switch(action.type) {
case 'DECREMENT_DATA':
return { ...state, data: state.data.filter((item) => item.id !== action.id), dataLength: state.data.length }
default:
return state;
}
}
export default data;动作
export function decrement() {
return {
type: 'DECREMENT_DATA',
id: 2
}
}组件
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { decrement } from '../actions/decrement';
class Decrement extends Component {
render() {
return (
<button onClick={this.props.decrement}>Decrement -</button>
);
}
}
const mapStateToProps = ((state) => {
return {
data: state.data
}
});
const mapDispatchToProps = ((dispatch) => {
return bindActionCreators({
decrement
}, dispatch)
});
export default connect(mapStateToProps, mapDispatchToProps)(Decrement);发布于 2018-10-15 12:27:21
在还原器中,您没有正确地更新长度,因为它是由当前状态列表而不是筛选列表确定的。
const data = (state = initialState, action) => {
switch(action.type) {
case 'DECREMENT_DATA':
const newList = state.data.filter((item) => item.id !== action.id)
return { ...state, data: newList, dataLength: newList.length }
default:
return state;
}
}发布于 2018-10-15 12:30:05
您应该返回这个:
case 'DECREMENT_DATA':
const updatedArray= state.data.filter((item) => item.id !== action.id)
return { ...state, data:updatedArray , dataLength: updatedArray.length }原因是当您使用state.data.length时,您仍在访问旧的状态值。
https://stackoverflow.com/questions/52816713
复制相似问题