reactjs - 使用 react/redux 编辑表单时如何在输入中显示当前值
问题描述
我正在从 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));
我希望看到我的输入包含当前项目的名称值,这样用户就可以在编辑之前看到它的当前值。
解决方案
您应该使用componentWillReceiveProps
组件生命周期。像这样
class ExerciseEdit extends React.Component {
componentWillReceiveProps(nextProps) {
if (nextProps.item.name) {
this.setState({ name: nextProps.item.name })
}
}
}
推荐阅读
- python - 列表索引超出范围,从文本文件中输出行
- php - 如何使用正文和标头制作 GuzzleHttp 发布请求?
- reactjs - Reactjs:为什么这在类组件中不起作用但在功能组件中起作用
- concurrency - 如何在 CPU 内核上执行函数,并在完成后获得回调?
- javascript - '(content: string, node: Element | null) => boolean | 类型的参数 空 | undefined' 不可分配给“Matcher”类型的参数
- python - 使用 Selenium 抓取嵌套的点击迷宫
- r - 捕获函数中输入值的名称
- php - 在 foreach 循环内自动增加会话索引
- c# - 如何将二进制表达式树从字符串转换为嵌套列表?
- github - Visual Studio 代码实时服务器扩展错误