2020.08.25

In the toodList case, the length of the state data has changed, but the data in the return is unchanged

In this case, hooks need to set setState to new objects or arrays.

The source code:

Const [searchData, setSearchData] = useState({})// Object type function handlerSearchData(name,value){searchData[name] = value;  setSearchData(setSearchData) }Copy the code

SetSearchData succeeds, but the return data is not updated.

Object type formatting requires the operator (…) , copy the new object value, and then set it.

The extension in the object passes through the operator (…) Retrieves all traversable properties from the parameter object and copies them to the current object.

The copy of an object instance by an extension operator is a shallow copy

The new writing structure is as follows:

const handlerSearchData = useCallback( (name, value) => { let a = { [name]: value } let newData = { ... searchData, ... a } setSearchData(newData) } )Copy the code

Add todo concat returns the new object

const [worksList, setWorksList] = useState([]) function addEidtWorks(value) { let newWorkList = worksList.concat({name:value}); setWorksList(newWorkList) setWord(''); / / or worksList. Push ({name: value}); setWorksList(()=>( [...worksList] )) setWord(''); }Copy the code

The specific type format is as follows:

Numeric types

import React, { useState } from 'react';

const Index = ()=> {
  const [count, setCount] = useState(0);

  return (
    <>
      <h2>{count}</h2>
      <button onClick={()=>(setCount(count+1))}>Add</button>
    </>
  );
}
Copy the code

Object type

import React, { useState } from 'react'; const Index = ()=> { const [obj, setObj] = useState({name:"zhangsan"}); return ( <> <h2>{obj.name}---{obj.age}</h2> <button onClick={()=> ( setObj({ ... obj, age:18 }) )}>change-obj</button> </> ); }Copy the code

An array type

import React, { useState } from 'react'; Const Index = ()=> {const [arr, setArr] = useState([1,2,3]); return ( <> <h2>{arr}</h2> <button onClick={()=>(setArr( setarr(()=> { arr.push(4); return [...arr] })>change-arr</button> </> ); }Copy the code

Function types

import React, { useState } from 'react';

const Index = ()=> {
  const [func, setFunc] = useState(()=> {
	return {name:'lisi'}
  });

  return (
    <>
	 <h2>{func}</h2>
    </>
  );
}
Copy the code

Func here refers to the return value of the function, if it returns a number, that’s a number, and if it returns an object type, that’s an object