为了账号安全,请及时绑定邮箱和手机立即绑定

React:无法在尚未安装的组件上调用 setState

React:无法在尚未安装的组件上调用 setState

倚天杖 2023-04-27 17:03:44
我正在使用 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 如何摆脱这个警告?
查看完整描述

2 回答

?
猛跑小猪

TA贡献1858条经验 获得超8个赞

componentDidMount您正在构造函数中调用生命周期方法,您不应该那样做。

这是问题所在:

this.componentDidMount = this.componentDidMount(this);

如果您在 中执行此操作constructor,您会收到该警告,React 会告诉您该组件尚未安装,但您已经setState通过手动调用componentDidMount.

在您的情况下,构造函数尚未完成执行,并且组件没有机会安装到 DOM 上。一旦构造函数被执行,组件就被初始化,然后组件被实际挂载到 DOM 上。

安装组件后,你的生命周期方法componentDidMount将由 React 以适当的上下文调用(因此不需要调用bindon componentDidMount),然后在那个时间点你应该调用setState来改变组件的状态。

您也可以删除_isMounted与该财产形式相关的 和检查componentDidMountcomponentWillUnmount因为它不是必需的。


查看完整回答
反对 回复 2023-04-27
?
斯蒂芬大帝

TA贡献1827条经验 获得超8个赞

componentDidMount 是一种生命周期方法,不需要在构造函数中进行初始化。删除它以避免警告。


  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); // remove this, componentDidMount is a lifecycle method.

  }


查看完整回答
反对 回复 2023-04-27
  • 2 回答
  • 0 关注
  • 90 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信