xml ui - state
useState
lets you use local state within a function component.
The setState
function is used to update the state. It accepts a new state value and enqueues a re-render of the component.
During subsequent re-renders, the first value returned by useState will always be the most recent state after applying updates.
Hooks can only be called at the top of components (they cannot be in conditionals, loops or nested functions)
Hooks can only be used within function components (they cannot be in normal JavaScript functions or class components)
const [state, setState] = useState(initialState);
() => {
const [age, setAge] = useState(19)
const handleClick = () => setAge(age + 1)
return (
<div>
Today I am {age} Years of Age
<div>
<button onClick={handleClick}>Get older! </button>
</div>
</div>
)
}
多个状态
() => {
const [age, setAge] = useState(19)
const [siblingsNum, setSiblingsNum] =
useState(10)
const handleAge = () => setAge(age + 1)
const handleSiblingsNum = () =>
setSiblingsNum(siblingsNum + 1)
return (
<div>
<p>Today I am {age} Years of Age</p>
<p>I have {siblingsNum} siblings</p>
<div>
<button onClick={handleAge}>
Get older!
</button>
<button onClick={handleSiblingsNum}>
More siblings!
</button>
</div>
</div>
)
}
状态为对象实例
//Nb: You have to pass the entire object to the useState updater function as the object is replaced NOT merged.
() => {
const [state, setState] = useState({ age: 19, siblingsNum: 4 })
const handleClick = val =>
setState({
...state,
[val]: state[val] + 1
})
const { age, siblingsNum } = state
return (
<div>
<p>Today I am {age} Years of Age</p>
<p>I have {siblingsNum} siblings</p>
<div>
<button onClick={handleClick.bind(null, 'age')}>Get older!</button>
<button onClick={handleClick.bind(null, 'siblingsNum')}>
More siblings!
</button>
</div>
</div>
)
}
// 🐢 setState (object merge) vs useState (object replace)
// assume initial state is {name: "Ohans"}
setState({ age: 'unknown' })
// new state object will be
// {name: "Ohans", age: "unknown"}
useStateUpdater({ age: 'unknown' })
// new state object will be
// {age: "unknown"} - initial object is replaced
{age: "unknown"} - initial state object is replaced
初始状态设置为函数返回值
() => {
const [token] = useState(() => {
let token = window.localStorage.getItem("my-token");
return token || "default#-token#"
})
return <div>Token is {token}</div>
}
之前的状态
() => {
const [count, setCount] = useState(0);
return (
<>
<p>Count value is: {count}</p>
<button onClick={() => setCount(0)}>Reset</button>
<button
onClick={() => setCount(prevCount => prevCount + 1)}>
Plus (+)
</button>
<button
onClick={() => setCount(prevCount => prevCount - 1)}>
Minus (-)
</button>
</>
);
}