我需要将表单提交数据从表单组件保存到父母的州。
我可以从父组件上的保存功能通过console.log记录数据,但是我似乎无法更改状态。
这是我的尝试:
父项:
import React, { Component } from "react";
import InputFormView from "./views/InputFormView";
class App extends Component {
constructor(props) {
super(props);
this.state = {
formData: '',
};
}
saveFormData = ( data ) => {
let newState = Object.assign({}, this.state);
newState.formData = data
console.log("formData: ")
console.log(newState) // I can see correct data here
this.setState(newState)
// this.setState({ formData : data }) // this also doesn't seem to update the state
setTimeout(() => {
console.log(this.state); // formData is empty
}, 3000);
};
render() {
return (
<div className="App">
<div className="container">
<InputFormView saveFormData={this.saveFormData} />
</div>
</div>
);
}
}
export default App;
子组件:
import React, { Component } from 'react';
class InputFormView extends Component {
saveData = e => {
e.preventDefault();
...
this.props.saveFormData(JSON.stringify(values));
}
render() {
return (
<React.Fragment>
...
<button onClick={this.saveData}>Save</button>
</React.Fragment>
);
}
}
export default InputFormView;
我想避免使用Redux,因为这是一个很小的应用程序。
如何从saveFormData函数更新父元素的状态?
答案 0 :(得分:1)
尝试一下:
class App extends Component {
constructor(props) {
super(props);
this.state = {
formData: '',
};
}
saveFormData = data =>
this.setState(state => ({...state, formData: data}), ()=> console.log(this.state));
render() {
return (
<div className="App">
<div className="container">
<InputFormView saveFormData={this.saveFormData} />
</div>
</div>
);
}
}
class InputFormView extends Component {
constructor(props) {
super(props);
this.state = {
myValue: 'hello'
};
}
saveData = e => {
e.preventDefault();
this.props.saveFormData(this.state);
}
handleChange = e => this.setState({myValue: e.target.value});
render() {
const {myValue} = this.state;
return (
<React.Fragment>
<input value={myValue} onChange={this.handleChange} />
<button onClick={this.saveData}>Save</button>
</React.Fragment>
);
}
}
答案 1 :(得分:0)
setState
是异步的,因此,如果要验证其是否正常工作,可以在其回调函数中进行:
saveFormData = (data) => {
this.setState({
formData: data
}, () => {
console.log(this.state)
});
};
答案 2 :(得分:0)
可以通过使用this.setState
函数中的先前状态参数来简化此操作。
saveFormData = ( data ) => {
this.setState((prevState) => { ...prevState, formData: data});
};