请问老师 为什么我用push的方法就不成功,老师视频里面用...解构的方式就可以

来源:2-6 React 中数据驱动的设计思想和事件绑定(2)

weixin_慕村1291783

2021-03-10 20:57:52

import React, { ComponentFragment } from "react";


class TodoList extends Component {

  constructor(props) {

    super(props);

    this.state = {

      inputValue: "",

      list: [13123],

    };

  }

  render() {

    return (

      <Fragment>

        <div>

          <input

            value={this.state.inputValue}

            onChange={this.handleChange.bind(this)}

            // onFocus={this.handleFocus.bind(this)}

          ></input>

          <button onClick={this.handleBtn.bind(this)}>提交</button>

        </div>

        <ul>

          {this.state.list.map((itemindex=> {

            return <li key={index}>{item}</li>;

          })}

        </ul>

      </Fragment>

    );

  }


  handleChange(e) {

    this.setState({

      inputValue: e.target.value,

    });

  }

  handleBtn() {

    console.log(13);


    // let newList = this.state.list.push("hhh");

    this.setState({

      list: this.state.list.push("hhh"),

    });

  }

  // handleFocus() {

  //   console.log(123);

  //   this.setState({

  //     inputValue: "",

  //   });

  // }

}


export default TodoList;


写回答

1回答

好帮手慕久久

2021-03-11

同学你好,解答如下:

push方法的返回值是追加元素后,数组的新长度,如下:

http://img.mukewang.com/climg/604977da09f3ddb405130174.jpg

http://img.mukewang.com/climg/604977e509e1efac05940145.jpg

如下这样写相当于把数组push后的长度赋值给list:

http://img.mukewang.com/climg/6049780609fe058e06360187.jpg

可以打印看一下:

http://img.mukewang.com/climg/60497826093aef9906790149.jpg

http://img.mukewang.com/climg/6049787309e648cb13720140.jpg

http://img.mukewang.com/climg/6049788609ae73ab06850161.jpg

由于list不再是数组了,所以就不能使用map方法了,因此报错:

http://img.mukewang.com/climg/604978be09de2eb006690159.jpg

而老师那样写,能保证list是数组,所以不会报错:

http://img.mukewang.com/climg/604978f109783ee607680137.jpg

祝学习愉快!

0

0 学习 · 15276 问题

查看课程