Reactjs 不使用setState react更新状态
提前感谢您查看我的问题。因此,我通过submitItem函数从CreateItem组件发布到DB,然后当承诺返回时,我调用pullAllItems来获取我的DB的categories表的所有行,以更新categories的状态: 反应组分:Reactjs 不使用setState react更新状态,reactjs,components,state,setstate,Reactjs,Components,State,Setstate,提前感谢您查看我的问题。因此,我通过submitItem函数从CreateItem组件发布到DB,然后当承诺返回时,我调用pullAllItems来获取我的DB的categories表的所有行,以更新categories的状态: 反应组分: import React, { Component } from 'react'; import CreateItem from './components/CreateItem'; import Categories from './components/
import React, { Component } from 'react';
import CreateItem from './components/CreateItem';
import Categories from './components/Categories';
// stylesheets
import './stylesheets/App.css';
class App extends Component {
constructor() {
super();
this.state = {
categories: [],
tasks: []
};
this.submitItem = this.submitItem.bind(this);
this.pullAllItems = this.pullAllItems.bind(this);
}
componentWillMount() {
fetch('/api/categories')
.then(res => res.json())
.then(res => {
this.setState({
categories: res
});
});
}
submitItem(title) {
const category = {
title
}
fetch('/api/categories', {
method: 'POST',
body: JSON.stringify(category),
headers: new Headers({
'Content-Type': 'application/json'
})
}).then(this.pullAllItems('categories'));
}
pullAllItems(type) {
const key = type;
let obj = {};
fetch('/api/' + type)
.then(res => res.json())
.then(res => {
obj[key] = res;
this.setState({
obj
}, () => {
console.log(this.state.categories);
});
});
}
render() {
return (
<div className="App">
<CreateItem submitItem={this.submitItem} />
<Categories categories={this.state.categories} pullAllTasks={this.pullAllItems}/>
</div>
);
}
}
import React,{Component}来自'React';
从“./components/CreateItem”导入CreateItem;
从“./组件/类别”导入类别;
//样式表
导入“./stylesheets/App.css”;
类应用程序扩展组件{
构造函数(){
超级();
此.state={
类别:[],
任务:[]
};
this.submitItem=this.submitItem.bind(this);
this.pullAllItems=this.pullAllItems.bind(this);
}
组件willmount(){
获取(“/api/categories”)
.then(res=>res.json())
。然后(res=>{
这是我的国家({
类别:res
});
});
}
次项(标题){
常量类别={
标题
}
获取(“/api/categories”{
方法:“POST”,
正文:JSON.stringify(类别),
标题:新标题({
“内容类型”:“应用程序/json”
})
}).然后(这个.pullAllItems('categories');
}
pullAllItems(类型){
常量键=类型;
设obj={};
获取('/api/'+类型)
.then(res=>res.json())
。然后(res=>{
obj[key]=res;
这是我的国家({
obj
}, () => {
log(this.state.categories);
});
});
}
render(){
返回(
);
}
}
如果我将响应记录在控制台日志中,我将获得附加的行,该行是使用submitItem函数发布的;但是,当我在pullAllItems函数中更新类别的状态时,状态不会更新(即使在setState的回调函数中也是如此)。我是一个新的反应者,我到处寻找我所缺少的东西,但在任何地方都找不到明确的答案。非常感谢您的帮助 我想你会想做
this.setState(obj)
,这样它们的动态键就会合并到状态中。在pullAllItems
中,this.setState({obj})
相当于this.setState({obj:obj})
。这几乎肯定不是你想要的。添加你正在做的submitItem的结尾:然后(This.pullAllItems('categories')
,这不应该是:然后(()=>This.pullAllItems('categories'))
?否则你就直接获取而不用等待承诺。另外,在submitAllItems()
中,(this.pullAllItems(…)
立即被调用。我假设您希望将调用推迟到fetch()
完成之后。您希望执行fetch(…)。然后(()=>this.pullAllItems())
。哦,上帝,你们都很对。在承诺返回后更改为调用pullAllItems。