I have a form component that is controlling its own state. In the form inputs the state set on the value attribute for name is coming back null. If I comment it out it moves to the next input value state and returns it null and so on. Anybody know whats going on here. Its been picking brain for a while now and I cant seem to figure it out. thanks for your help.
constructor(props){
super(props)
this.State = {
name: "",
nickname: "",
position: "",
id: Date.now(),
description: ""
};
}
handleChange = (event) => {
event.persist()
this.setState((state) => {
return {
...state,
[event.target.name] : event.target.value
}
})
}
onSubmit = (e) => {
this.setState({ ...this.state });
e.preventDefault();
this.props.putSmurfData();
console.log(this.props);
// alert (`${this.state.position} ${this.state.name} ${this.state.description} ${state.nickname}`)
};
render() {
console.log(this.state);
return (
<section>
<h2>Add Smurf</h2>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label htmlFor="name">Name:</label>
<br />
<input
onChange={this.handleChange} name="name"
id="name"
eslint-disable-next-line
value={this.state.name}/>
<label htmlFor="description">Description:</label> <br />
<input
onChange={this.handleChange}
name="description"
id="description"
//eslint-disable-next-line
value={this.state.description}
/>
<label htmlFor="nickname">NickName:</label>
<br />
<input
onChange={this.handleChange}
name="nickname"
id="nickname"
//eslint-disable-next-line
value={this.state.nickname}
/>
<label htmlFor="position">Position:</label>
<br />
<input
onChange={this.handleChange}
name="position"
id="position"
//eslint-disable-next-line
value={this.state.position}
/>
</div>
<div
data-testid="errorAlert"
className="alert alert-danger"
role="alert"
>
{this.props.isLoading ? <p>Loading Smurfs...</p> : null}
Error:
{this.props.error ? (
<p style={{ color: "red" }}>{this.props.error}</p>
) : null}
</div>
<button>Submit Smurf</button>
</form>
</section>
);
}
}
export default connect(null, { putSmurfData })(AddForm);
question from:
https://stackoverflow.com/questions/65952709/cant-read-property-name-of-null-react-redux 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…