1. 程式人生 > 程式設計 >React實現todolist功能

React實現todolist功能

一、index.js

ReactDOM.render(
 <React.StrictMode>
  <TodoList />
 </React.StrictMode>,document.getElementById('root')
);

二、TodoList

1、constructor

constructor(props) {
    super(props);
    this.state = {
      inputValue: '',list: []
    }
  }

2、render

 render() {
    return (
      <React.Fragment>
        <div>
          {/*label標籤的作用,擴大點選範圍*/}
          <label htmlFor='insertArea'>輸入內容</label>
          <input
            id='insertArea'
            className={'inputStyle'}
            value={this.state.inputValue}
            onChange={event => this.handleInputChangle(event)}/>
          <button onClick={event => this.handleButtonVlue(event)}>提交</button>
          <hr/>
          <ul>
            {this.getTodoList()}
          </ul>
        </div>
      </React.Fragment>
    )
  }

3、getTodoList

getTodoList() {
    return (
      this.state.list.map((value,index) => {
        return <TodoItem2
          key={index}
          itemVlue={value}
          itemIndex={index}
          itemDelete={this.handleItemDelete.bind(this)}>
          {/*這塊需要強制繫結為父元件的this,否則在子元件中找不到*/}
        </TodoItem2>
      })
    );
  }

4、事件函式

 /**
   * 監聽輸入框變化
   **/
  handleInputChangle(e) {
    const value = e.target.value;
    this.setState(() => ({
      inputValue: value
    }))
  }
 
  /**
   * 監聽點選按鈕
   **/
  handleButtonVlue(e) {
    this.setState((prevStatus) => ({
      list: [...prevStatus.list,this.state.inputValue],inputValue: ''
    }))
  }
 
  /**
   * 監聽點選item刪除
   **/
  handleItemDelete(index) {
    this.setState((preStatus) => {
      const list = [...preStatus.list];
      list.splice(index,1)
      return {
        list
      }
    });
  }

5、網路請求

使用Charles代理網路,安裝證書,設定埠,在手機上面開啟網路WIFI,設定代理IP和埠,這樣就能監聽到手機訪問的網路,攔截請求,代理本地地址,返回本地資料。

React實現todolist功能

需要注意的是charles識別不出來localhost,需要在package.json中改成設定:

* "start": "set PORT=3000 HOST=localhost.charlesproxy.com && react-scripts start",

訪問時候使用:

http://localhost.charlesproxy.com:3000/

(1)引入axios

yarnyarnaddaxios

(2)在componentDidMount進行網路請求

 /**
   * 這塊進行網路請求
   */
  componentDidMount() {
    axios.get('api/todolist')
      .then((res) => {
        this.setState({
          list: [...res.data]
        })
      }).catch(() => {
      alert('發生錯誤')
    })
  }

這樣執行程式的時候初始值就有了資料了。

總結:當前元件的state或者prop發生改變的時候,App中的render函式就會重新執行。做到資料和頁面同步。當父元件發生變化重新執行的時候,子元件的render也會被重新執行一次。

到此這篇關於React實現todolist功能的文章就介紹到這了,更多相關React實現todolist內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!