【发布时间】:2019-08-15 12:49:37
【问题描述】:
我正在从 MongoDB (mLab) 实例中提取数据。
当我去编辑一个项目时,我希望当前项目的值(在加载此组件之前已经在我的 redux 存储中的数据)显示在此处的输入上:
我已经测试了将组件的状态设置为诸如 ```state = { name: this.props.item.name || "" }``
就是这样。我想如果我在渲染时将值加载为状态,输入的值就会出现在那里。
import _ from "lodash";
import React from "react";
import InputField from "components/inputs/InputField";
import { withRouter, Link } from "react-router-dom";
import { connect } from "react-redux";
import { editExercise } from "actions/exerciseActions";
class ExerciseEdit extends React.Component {
state = { name: "" };
onChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
onSubmit = e => {
e.preventDefault();
const { history } = this.props;
const { id, exerciseId } = this.props.match.params;
const exerciseProps = { ...this.state };
console.log(this.props.match.params);
this.props.editExercise(id, exerciseId, exerciseProps, history);
};
render() {
const { errors } = this.props;
return (
<div>
<h1 className="title is-3">Edit your exercise</h1>
<form onSubmit={this.onSubmit}>
<InputField
label="Name"
name="name"
type="text"
value={this.state.name}
onChange={this.onChange}
errors={errors}
/>
<Link
to={`/workouts/${this.props.match.params.id}`}
className="button is-danger is-large"
style={{ marginTop: "20px" }}
>
Cancel
</Link>
<button
type="submit"
className="button is-primary is-large"
style={{ marginTop: "20px" }}
>
Submit
</button>
</form>
</div>
);
}
}
const mapStateToProps = ({ workouts }) => {
return { workouts };
};
export default connect(
mapStateToProps,
{ editExercise }
)(withRouter(ExerciseEdit));
我希望看到我的输入包含当前项目的名称值,这样用户就可以在编辑之前看到它的当前值。
【问题讨论】:
-
为什么不把ExerciseEdit的状态移到redux store?
-
难道我不必在每次击键时调用动作创建者,然后用输入值更新我的商店吗?还是您的意思是将最终价值存储在我的商店中?我使用的值可以从我的 MongoDB 数据中获取。
-
是的,我的意思是完全删除状态。乍一看并不好听。但你将有权做任何事情!一个单一的事实来源。