嗨,我在react中使用redux,我有一个表单,并且表单数据(特别是用户键入内容时表单元素的值)存储在我的react组件的本地状态内。同时我有一个调度,将一个计数器加一,并且在窗体元素上调用onchanged函数时调用它。我展示了从redux状态获取的计数器数据。因此,存储在redux中的数据是按下的键数。 问题是无法将计数器的值输入到表单输入中。例如,如果我按任意键(例如,键入一个字母),则我的redux计数器值将为1,现在我无法在输入中键入数字1。本地状态不变。 这是我的代码:
import * as React from 'react';
import {Box} from "@material-ui/core";
import {FormElements} from "../forms/formElements";
import Typography from "@material-ui/core/Typography";
import {NavLink} from "react-router-dom";
import {connect} from "react-redux";
import ClickAwayListener from "@material-ui/core/ClickAwayListener";
class Login extends React.Component {
state = {
counter: 0,
comps: {
Lusername: {
required: true,
label: "username",
id: "Lusername",
type: "string",
value: ""
},
Lpassword: {
required: true,
type: "password",
id: "Lpassword",
label: "password",
value: ""
}
}
}
handleChange = (event) => {
this.props.onInc(); //redux dispatch
let {id, value} = event.target //local state
let comps = this.state.comps
comps[id].value = value
this.setState({comps: comps})
}
render() {
return (
<ClickAwayListener onClickAway={this.props.onclickAway}>
<Box m={2}>
<p>{this.props.ctr}</p>
<FormElements comps={this.state.comps} handleChange={this.handleChange}
handleSubmit={this.handleSubmit}></FormElements>
<Box mt={2}>
<NavLink to={"/signup"} style={{textDecoration: "none", color: "#0e404c"}}>
<Typography component={"h5"}>don't have an account? signUp</Typography>
</NavLink>
</Box>
</Box>
</ClickAwayListener>
);
};
};
const MapStateToProps = state => {
return {ctr: state.counter}
}
const MapDispatchToProps = dispatch => {
return {
onInc: () => dispatch({type: "INC"})
}
}
export default connect(MapStateToProps, MapDispatchToProps)(Login)