Reactjs 一次保存所有状态值
我试图在一个状态中同时存储3个不同的状态值(类别、子类别、平方英尺),并将它们一起保存在数据库中。我有3个不同的函数用于3个不同的状态。现在我对3个不同的功能提出了3个axios请求:Reactjs 一次保存所有状态值,reactjs,state,Reactjs,State,我试图在一个状态中同时存储3个不同的状态值(类别、子类别、平方英尺),并将它们一起保存在数据库中。我有3个不同的函数用于3个不同的状态。现在我对3个不同的功能提出了3个axios请求: this.state = { apiUrl: config.publicRuntimeConfig.publicRuntimeConfigValue.apiUrl, categoryName:'', subCategoryName:'', squareFeet:'', };
this.state = {
apiUrl: config.publicRuntimeConfig.publicRuntimeConfigValue.apiUrl,
categoryName:'',
subCategoryName:'',
squareFeet:'',
};
saveValue = (e) => {
console.log('savecategory', e.target.innerHTML);
this.setState({
category: e.target.innerHTML
}, this.makingAxiosRequest);
};
makingAxiosRequest = () => {
axios.post( this.state.apiUrl+'/api/v1/LeadSurvey/save', {
'categoryName':this.state.category,
}, {})
};
savedValue = (e) => {
// console.log('savecategory', e.target.innerHTML);
this.setState({
subCategory: e.target.innerHTML
}, this.makeAxiosRequest);
};
makeAxiosRequest = () => {
axios.post( this.state.apiUrl+'/api/v1/LeadSurvey/save', {
'subCategoryName':this.state.subCategory,
}, {})
};
handleChange = value => {
this.setState({
value: value
})
};
savingValue = () => {
console.log('saveValue ...', this.state);
axios.post( this.state.apiUrl+'/api/v1/LeadSurvey/save', {
'squareFeet':this.state.value,
}
但我无法在最后一个状态中传递所有此值并立即保存。检查是否传递了正确的状态名称。试试这样的
axios.post(this.state.apiUrl+'/api/v1/LeadSurvey/save', {'categoryName':this.state.categoryName,subCategoryName:this.state.subCategoryName,'squareFeet':this.state.squareFeet});
一次传递所有状态数据,而不是3次不同的调用。
如果这3个值取自输入字段,则可以将这些值与如下状态绑定
onChange=(e,{name,value})=>{
this.setState({[name]:value});
}
<input name="categoryName" onChange={this.onChange}/>
onChange=(e,{name,value})=>{
this.setState({[name]:value});
}
为您的输入或正在使用的内容提供name
属性,然后调用onChange(e)
passing event属性,从event获取name、value属性,并将其设置为如下状态:
class Thingy扩展了React.Component{
建造师(道具){
超级(道具)
this.state={};
}
onChange(e){
this.setState({[e.target.name]:e.target.value});
}
render(){
const{title}=this.props;
返回(
名称
this.onChange(e)}/>
年龄
this.onChange(e)}/>
);
}
}
//渲染它
ReactDOM.render(
,
文件正文
);代码>