简体   繁体   中英

How to use setState function inside the function in functional component?

I am now working on a functional component

const [input_error, setInputError] = useState({
harvest:false,
stake:false,
unstake:false,
deposit:false,
withdraw:false,    
apy:false,
period:false,
feeaddress:false,
harvestfee:false,
unstakefee1:false,
unstakefee2:false,
unstakefee3:false,
unstakefee4:false,
unstakefee5:false,

});

function set_value(e) {
let temp = JSON.parse(JSON.stringify(input_value));
temp[e.target.name] = e.target.value;
setInputValue(temp);}

At this time, I cannot use set_value(e) to modify the state and render it correctly.

Because the state is object and you should use json to set the state. So JSON.parse(JSON.stringify(input_value));

to string and to json again.

If you are using react, I don't recommend doing this for immutability, use the spread operator like this:

setInputError({...input_error, [e.target.name]:e.target.value})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM