React 16.9
我知道这class component state
:
class JustAnotherCounter extends Component {
state = {
count: 0
};
相当于使用HooksuseState
:
function JustAnotherCounter() {
const [count, setCount] = useState(0);
..但是下面使用HooksuseState
的类组件状态等效于什么?
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('');
另一种选择是使用化简器,它可以做成一个比这复杂得多的例子:
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' });
您可以使用 State 来启动对象,如下所示:
function Main() {
const [form, setValues] = useState({
step: 1,
firstName: '',
lastName: '',
jobTitle: '',
jobCompany: '',
jobLocation: '',
})
}
然后要设置值,您可以执行以下操作
setValues({
...form,
firstName: 'Andrew',
})
运行 { npm install react-multi-state } 看看它有多简单易用
import { Fragment } from 'react'
function Counter() {
const [state, setState, { setCount }] = useMultiState({
count: 0,
secondCount: 10,
})
return (
<Fragment>
<button onClick={() => setCount(c => c + 1)}>Update count</button>
<button
onClick={() => {
setState(prevState => ({
secondCount: prevState.secondCount + 10,
// use as many `prevState` property values as you wish
}))
}}
>
Update second count
</button>
</Fragment>
)
}
您可以轻松地单独更新状态
https://github.com/whizkydee/react-multi-state/
您可以将状态值另存为对象。
请记住,当您使用 setState 更新对象值时,您必须创建一个新对象而不是更新现有对象的值,因为 setState 比较对象的引用值,而不是比较对象值。这与使用 React 类组件不同。
参考: https://reactjs.org/docs/hooks-faq.html#should-i-use-one-or-many-state-variables
将状态另存为对象
const [state, setState] = useState({ left: 0, top: 0, width: 100, height: 100 });
...
// deep clone your object (use other package like lodash or ramda for better performance)
const newObj = JSON.parse(JSON.stringify(state))
// update value and set state
newObj.top = 28
setState(state);
或对单行集状态使用扩展
// Spreading "...state" ensures we don't "lose" width and height
setState(state => ({ ...state, left: e.pageX, top: e.pageY }));