react-Hooks与生命周期的关系以及使用hooks做一个todolist

非常多的案例详情见添加链接描述

  • useState

  • num:状态值

  • setNum:相当于原来的setState,修改num的状态

  • useState(0):默认值,num=0

const [num,setNum] = useState(0);
import React ,{ useState} from 'react'

export default () => {
    const [num,setNum] = useState(0);
    return (
        <div>
            {num}
            <button onClick={()=>{setNum(num+1)}}>Add</button>
        </div>
    )
}
  • useEffect

一个函数包含了三个生命周期的操作

componentDidMount=>
componentDidUpdate=>
componentWillUnmount

在这段代码中,表示在componentDidMount中执行了 document.title = ${count} times

export default () =>{
    const [count,setCount] = useState(0);
    useEffect(()=>{
        document.title = `${count} times`
    })
        return(
            <div>
                <span>{count}</span>
                <button onClick={()=>{setCount(count+1)}}>Add</button>
            </div>
        )
}

Todolist:

  • 遇到的问题

点击增加或者别的功能键后,页面数据重新加载了,也就是组件更新渲染后执行useEffect重新请求数据,又重新设置了数据,造成了死循环。

  • 解决方法:给useEffect传入一个空数组作为第二个参数,只在组件挂载的时候执行。

  • Action知识点—useEffect的第二个参数:

  • 设置为[ ]时,相当于生命周期函数 componentDidMount;

  • 没有第二个参数时,相当于 componentDidMount、componentDidUpdate=>就会造成上述提到的问题,数据更新后反复重新渲染

  • [ count ],当第二个参数有值时,只监听该值的变化,count发生变化才会触发componentDidUpdate

  • return :当第二个参数为return时,相当于componentWillUnmount,如下

  • useEffect(() => { return () => { console.log('will unmount'); } }, []);
    当在 useEffect 的回调函数中返回一个函数时,这个函数会在组件卸载前被调用。我们可以在这里面清除定时器或事件监听器。

import React ,{ useState,useEffect, Component} from 'react';
import axios from 'axios';
import {Table , Space, Button ,Switch, Popconfirm} from 'antd'
import Addlist from './Addlist'
const Todolist = () => {
    const [ list,setList ] = useState([]);
    const columns = [
        {
          title: 'Title',
          dataIndex: 'title',
          key: 'title',
         render: (title, record) => {
           return (
           <span>{record.title}</span>
           )
         }
        },
        {
          title: 'isTodo',
          dataIndex: 'isTodo',
          key: 'isTodo',
          render: (title, record) => {
            return (
            <span>{record.isTodo+""}</span>
            )
          }
        },
        {
          title:'Statu',
          dataIndex:'isTodo',
          key:'Statu',
          render:(text,record) => {
            return <Switch defaultChecked={record.isTodo} onChange={()=>{changeTodo(record.id)}}></Switch>
          }
        },
        {
          title: 'Action',
          key: 'action',
          render: (text,record) => (
              <Space size="middle">
                <Popconfirm placement="right" title="Sure?" onConfirm={()=>{deleteList(record.id)}} okText="Yes" cancelText="No">
                <Button>Delete</Button>
                </Popconfirm>
              </Space> 
          ),
        },
      ];
    const addList = (data,id) =>{
            let newthingInfo={
                    title:data,
                    id:id+'',
                    isTodo:false
                }
                const newlist=[...list,newthingInfo];
                setList(newlist);
            }
    const changeTodo = (id) => {
        let newlist=[...list].filter(item => item.id==id);
        newlist[0].isTodo=!newlist[0].isTodo;
        let newlists=[...list].filter(item => item.id!=id);
        newlists.push(newlist[0]);
        setList(newlists);
    }
    const deleteList = (id) => {
        let newlist=[...list].filter(item => item.id!=id);
        setList(newlist)
    }
    useEffect( async ()=>{
        await axios.get('http://easy-mock.sftcwl.com/mock/5f216313fc8545fbfadc239d/example_copy/restful/:id/list',{dataType:"json"})
        .then(res=>{
            setList(res.data.data)
        }).catch(err=>{
            console.log(err)
        })
    },[]);
    return(
        <>
            <div className="todolist">
                <Addlist newvalue={addList}/>
            </div>
                <Table columns={columns} dataSource={list} rowKey={record => record.id}/>
        </>
    )
}

export default Todolist;
import React, { Component, Fragment } from 'react'
import '../asset/todolist.css'
import { Input ,message } from 'antd';
import axios from 'axios';
let querystring = require('querystring');
let id="3"
class Addlist extends React.Component{
    constructor(props){
        super(props);
    };
    keyEnter=async(e)=>{
        if(e.keyCode===13){
            id++;
            let titlevalue=e.target.value;
            let newlist={
                title:e.target.value,
                id:id+'',
                isTodo:false
            }
            await axios.post('http://easy-mock.sftcwl.com/mock/5f22e310fc8545fbfadc240d/example_copy_copy/upload',querystring.stringify(newlist))
            .then(res=>{
                this.props.newvalue(titlevalue, id);
                message.success('This is a success message',[1]);
            }).catch(err=>{
                message.error('This is an error message',[1]);
            })
        }
    }
    render(){
        return(
            <Fragment>
                    <header>Todolist</header>
                    <div className="newtodo">
                        <Input type="text" placeholder="what to do" onPressEnter={this.keyEnter}></Input>
                    </div>
            </Fragment>
        )
        

    }
}
export default Addlist

你可能感兴趣的:(react-Hooks与生命周期的关系以及使用hooks做一个todolist)