一、index.js
1
2
3
4
5
6
|
ReactDOM.render( <React.StrictMode> <TodoList /> </React.StrictMode>, document.getElementById( 'root' ) ); |
二、TodoList
1、constructor
1
2
3
4
5
6
7
|
constructor(props) { super (props); this .state = { inputValue: '' , list: [] } } |
2、render
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
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
1
2
3
4
5
6
7
8
9
10
11
12
13
|
getTodoList() { return ( this .state.list.map((value, index) => { return <TodoItem2 key={index} itemVlue={value} itemIndex={index} itemDelete={ this .handleItemDelete.bind( this )}> { /*這塊需要強制綁定為父組件的this,否則在子組件中找不到*/ } </TodoItem2> }) ); } |
4、事件函數
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
/** * 監聽輸入框變化 **/ 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和端口,這樣就能監聽到手機訪問的網絡,攔截請求,代理本地地址,返回本地數據。
需要注意的是charles識別不出來localhost,需要在package.json中改成設置:
* "start": "set PORT=3000 HOST=localhost.charlesproxy.com && react-scripts start",
訪問時候使用:
http://localhost.charlesproxy.com:3000/
(1)引入axios
yarn yarn add axios
(2)在componentDidMount進行網絡請求
1
2
3
4
5
6
7
8
9
10
11
12
13
|
/** * 這塊進行網絡請求 */ componentDidMount() { axios.get( 'api/todolist' ) .then((res) => { this .setState({ list: [...res.data] }) }). catch (() => { alert( '發生錯誤' ) }) } |
這樣運行程序的時候初始值就有了數據了。
總結:當前組件的state或者prop發生改變的時候,App中的render函數就會重新執行。做到數據和頁面同步。當父組件發生變化重新執行的時候,子組件的render也會被重新執行一次。
到此這篇關于React實現todolist功能的文章就介紹到這了,更多相關React實現todolist內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/yoonerloop/article/details/111711291