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

我正在尝试在功能组件和基于类的组件中制作待办事项应用程序;


在函数


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: "",

        });

    }


慕森卡
浏览 143回答 3
3回答

阿晨1998

我认为this.state.items((prevList) => [...prevList, newItem])是错误的。你可以尝试将其更改为[...this.state.items, newItem]因为this.state.items没有功能吗?

largeQ

在 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

元芳怎么了

您的代码的问题在于它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: "",));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript