gpt4 book ai didi

javascript - 如何在 ReactJs 中使用 Hooks useState 编写多行状态

转载 作者:行者123 更新时间:2023-12-02 07:57:26 24 4
gpt4 key购买 nike

React 16.9

我知道这个类组件状态:

class JustAnotherCounter extends Component {
state = {
count: 0
};

相当于使用Hooks useState:

function JustAnotherCounter() {
const [count, setCount] = useState(0);

..但是下面使用 Hooks useState类组件状态会是什么?:

class Main extends Component {
state = {
step: 1,
firstName: '',
lastName: '',
jobTitle: '',
jobCompany: '',
jobLocation: '',
}

任何帮助将不胜感激。

最佳答案

您可以使用与类组件相同的总体思路,但请记住您需要自己传播对象。

   const [state, setState] = useState({
step: 1,
firstName: '',
lastName: '',
jobTitle: '',
jobCompany: '',
jobLocation: '',
});
// Setting state like:
setState(prev=>{...prev,firstName:'Joey'});

您还可以设置多个设置状态调用

const [step,setStep] = useState(1);
const [firstName,setFirstName] = useState('');
const [lastName,setLastName] = useState('');
const [jobTitle,setJobTitle] = useState('');
const [jobCompany,setJobCompany] = useState('');
const [jobLocation,setJobLocation] = useState('');

另一个选择是使用reducer,它可以做成比这个复杂得多的例子:

const [state, dispatch] = useReducer(
(state, action) => ({ ...state, [action.name]: action.value }),
{
step: 1,
firstName: '',
lastName: '',
jobTitle: '',
jobCompany: '',
jobLocation: '',
}
);
// Then update values using:
dispatch({ name: 'firstName', value: 'Joey' });

关于javascript - 如何在 ReactJs 中使用 Hooks useState 编写多行状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62012191/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com