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

如何将函数挂钩转换为类状态

如何将函数挂钩转换为类状态

慕森卡 2022-10-13 16:15:45
我正在尝试在功能组件和基于类的组件中制作待办事项应用程序;在函数function addTodo(event) {    event.preventDefault();    if (!text.length) {      return alert("Plese Write a todo");    }    const newItem = {      text: text,      id: Date.now(),    }    setItems(prevList => [...prevList, newItem])    console.log(newItem);    setText("");    inputRef.current.focus();  }但是在课堂上,当我设置项目的状态时,它给了我一个错误    addTodo(event) {        event.preventDefault();        if (!this.state.text.length) {            return alert("Plese Write a todo");        }        const newItem = {            text: this.state.text,            id: Date.now()        }        this.setState({            items: this.state.items((prevList) => [...prevList, newItem]),            text: "",        });    }
查看完整描述

3 回答

?
阿晨1998

TA贡献2037条经验 获得超6个赞

我认为this.state.items((prevList) => [...prevList, newItem])是错误的。

你可以尝试将其更改为[...this.state.items, newItem]因为this.state.items没有功能吗?


查看完整回答
反对 回复 2022-10-13
?
largeQ

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

在 react 中基于类的组件中,您需要将函数绑定到类构造函数中的类才能使用 this 关键字。


constructor(props){

  super(props);

  this.addTodo = this.addTodo.bind(this); // add this line

}

现在你可以在 addTodo 函数中使用 this.setState 了。还有另一种不需要绑定它的方法。您可以使用箭头功能代替普通功能。


   addTodo = (event) => {    //just modify this line

        event.preventDefault();


        if (!this.state.text.length) {

            return alert("Plese Write a todo");

        }


        const newItem = {

            text: this.state.text,

            id: Date.now()

        }


        this.setState({

            items: this.state.items((prevList) => [...prevList, newItem]),

            text: "",

        });

    }

您可以在此处阅读有关常规函数和箭头函数之间差异的更多信息 - https://medium.com/better-programming/difference-between-regular-functions-and-arrow-functions-f65639aba256


查看完整回答
反对 回复 2022-10-13
?
元芳怎么了

TA贡献1798条经验 获得超7个赞

您的代码的问题在于它this.state.items是一个数组,而不是一个接受回调的函数。


this.setState({

  items: this.state.items((prevList) => [...prevList, newItem]),

  text: "",

});

使用 setter from 时useState,您将当前状态作为回调参数获取,如 中所示setItems(prevList => [...prevList, newItem])。


在基于类的setState中,您在那里获得回调参数,而不是您访问项目的位置。


对于您的代码,您需要:


this.setState(state => (

  items: [...state.items, newItem],

  text: "",

));


查看完整回答
反对 回复 2022-10-13
  • 3 回答
  • 0 关注
  • 142 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号