我正在使用 react(MERN stack) 创建一个简单的待办事项应用程序。当我尝试同时使用 axios 和 setState 调用 get API 时出现上述警告。我已经通过堆栈溢出的其他线程解决了同样的问题,但没有一个真正有用。我什至试过弄乱“isMounted”变量。下面是我的代码...
export default class App extends React.Component{
_isMounted = false;
constructor(props){
super(props);
this.state = {list:[], itemCounter: 0};
this.addItem = this.addItem.bind(this);
this.handleDone = this.handleDone.bind(this);
this.componentDidMount = this.componentDidMount(this);
}
componentDidMount(){
this._isMounted = true;
axios.get(`http://localhost:8000/todo/api/`)
.then(res => {
if(this._isMounted){
const list = res.data;
const unDoneList = list.filter(task => task.done === false)
this.setState({ list: list, itemCounter: unDoneList.length });
}});
}
componentWillUnmount() {
this._isMounted = false;
}
addItem(val) {
axios.post('http://localhost:8000/todo/api/task/', { data: val })
.then(res => {
const itemCounter = this.state.counter + 1;
const updatedList = this.state.list;
updatedList.push({ data: val, done: false });
console.log(res);
console.log(res.data);
this.setState({ list: updatedList, itemCounter: itemCounter });
})
}
handleDone(item){
console.log(item._id)
axios.post(`http://localhost:8000/todo/api/delete/${item._id}`)
.then(() => console.log("Item Deleted."));
let updatedList = this.state.list;
updatedList.forEach(task => {
if(task.id === item.id ){
task.done = true;
}
});
const itemCounter = this.state.itemCounter - 1;
this.setState({ list: updatedList, itemCounter: itemCounter });
}
作为参考,我已经在 GitHub 上上传了我的整个项目: https: //github.com/mohnishm/Todo-App-in-React 如何摆脱这个警告?
猛跑小猪
斯蒂芬大帝
相关分类