我正在使用 Redux 构建一个应用程序,但我遇到了这个问题:当我向其添加元素时,我的减速器的状态会更新,但显示保持不变。
这是我的组件的代码:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { displayList } from '../actions';
import { bindActionCreators } from 'redux';
class ListDisplayer extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="container">
<form>
<div className="field is-grouped">
<div className="control">
<button className="button is-primary"
onClick={(e) => {e.preventDefault();this.props.dispatch(displayList())}}>
Display
</button><br/>
List
{
this.props.list.map((item,index) =>
<p key={index}>{item}</p>
)
}
</div>
</div>
</form>
</div>
)
}
}
function mapStateToProps(state){
return {
list: state.displayReducer,
};
}
function mapDispatchToProps(dispatch) {
return { actions: bindActionCreators(displayList, dispatch) }
}
export default connect(mapStateToProps)(ListDisplayer);
Run Code Online (Sandbox Code Playgroud)
为了测试问题是否来自减速器,我以这种方式初始化它:
import * as actionType from '../actions/ActionType';
const displayReducer = (state = ['haha','haha','haha'], action) => {
let newState;
switch (action.type) {
case actionType.DISPLAY_LIST:
let newarr = state;
newarr.push(action.payload);
console.log(newarr);
return newState = newarr;
default:
return state
}
}
export default displayReducer;
Run Code Online (Sandbox Code Playgroud)
但是,当我单击 Display 按钮并执行 displayList() 函数时(参见组件代码),如控制台所示,reducer 的状态更新:
但是,屏幕上仍然只有三个 'haha',这意味着我的 mapStateToProps 无法正常工作,或者我没有在 reducer 中正确更新状态。我已经在这个网站和 GitHub 上看到过类似的错误,但没有一个解决方案对我有用。
小智 5
引用“Redux”文档
为什么我的组件没有重新渲染,或者我的 mapStateToProps 没有运行? 到目前为止,不小心直接改变或修改您的状态是组件在分派操作后不重新渲染的最常见原因
欲了解更多信息,请访问网站
所以基本上,下面的代码片段
let newarr = state;
newarr.push(action.payload);
console.log(newarr);
Run Code Online (Sandbox Code Playgroud)
改变原始状态本身
为什么?因为
1) Array.push() 方法对原数组进行变异(同时返回新数组的长度)
2)在Javascript中,当一个变量引用一个对象(包括数组)时,“值”就是对这个对象的引用。也就是说,每当你执行newarr.push(newItem),如果你控制台日志(state)你就可以看到,同样的项目也包含在状态本身中。但事实并非如此。
为了防止意外变异,你应该做到以下几点,
let newarr = [...state, action.payload]
使用扩展运算符,您可以利用状态数组中的值,并且在逗号之后,您还引入了一个新值,该值将作为新项添加。
由于这种方式,您不必使用newarr.push()方法并改变数组,而是创建一个新数组,复制旧状态的值并在此复制过程中引入新值
总而言之,您可以尝试像这样更新代码吗
const displayReducer = (state = ['haha','haha','haha'], action) => {
let newState; // you don't need this, you can get delete this line
switch (action.type) {
case actionType.DISPLAY_LIST:
return [...state, action.payload] // return a new array that copies the original state's values and introduces a new value during this process
default:
return state
}
}
Run Code Online (Sandbox Code Playgroud)