gpt4 book ai didi

reactjs - 在这个 redux reducer 中使用 Object.assign 的目的是什么?

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

我知道状态应该是不可变的,这是一个禁忌,通过推送改变状态,

//action = Object {type: "CREATE_COURSE", course: {title: algebra}}

export default function courseReducer(state = [], action) {
switch(action.type) {
case 'CREATE_COURSE':

state.push(action.course)
return state;

default:
return state;
}
}

Pluralsight recommends this:

export default function courseReducer(state = [], action) {
switch(action.type) {
case 'CREATE_COURSE':
return [...state,
Object.assign({}, action.course)
];

default:
return state;
}
}

但是不使用 object.assign 有什么问题呢?这有什么问题,似乎该应用程序仍然有效。 state 仍然没有被改变,一个新的数组被返回。

export default function courseReducer(state = [], action) {
switch(action.type) {
case 'CREATE_COURSE':
return [...state,
action.course
];

default:
return state;
}
}

类(class) Action :

export function createCourse(course) {
return { type: 'CREATE_COURSE', course};
}

类(class)页面组件:

import React, {PropTypes} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as courseActions from '../../actions/courseActions';

class CoursesPage extends React.Component {
constructor(props, context) {
super(props, context);

this.state = {
course: { title: '' }
};

this.onTitleChange = this.onTitleChange.bind(this);
this.onClickSave = this.onClickSave.bind(this);
}

onTitleChange(event) {
const course = this.state.course; // assign this.state.course to course
course.title = event.target.value; // reassign course.title to whatever was in input
this.setState({course: course}); // reassign state course to new course object with updated title
}

onClickSave() {
this.props.actions.createCourse(this.state.course);
}

courseRow(course, index) {
return <div key={index}>{course.title}</div>;
}
render() {
return (
<div>
<h1>Courses</h1>
{this.props.courses.map(this.courseRow)}
<h2>Add Course</h2>
<input
type="text"
onChange={this.onTitleChange}
value={this.state.course.title} />
<input
type="submit"
value="Save"
onClick={this.onClickSave} />
</div>
);
}
}

CoursesPage.propTypes = {
courses: PropTypes.array.isRequired,
actions: PropTypes.object.isRequired
};

function mapStateToProps(state, ownProps) {
return {
courses: state.courses
};
}

function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(courseActions, dispatch)
};
}

export default connect(mapStateToProps, mapDispatchToProps)(CoursesPage);

最佳答案

如果您不使用 Object.assign,新数组的最后一个元素将是对 action.course 的引用以及任何引用。传递引用可能工作正常,但如果某处发生变异并导致问题 - 它们将很难调试。安全总比遗憾好。

关于reactjs - 在这个 redux reducer 中使用 Object.assign 的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39054523/

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