我想在我的组件中有一个初始状态,但我需要根据一个复杂的if/else语句来设置它.
使用嵌套的三元组语句很快就会变得不可读和不可管理.由于状态应该是 top-level ,所以我不能直接在组件中编写if/Else语句.
例如,假设我需要根据一些给定的属性、从本地存储、从URL、从会话状态或从Cookie设置选定国家/地区的初始状态:
const SomeComponent = ({ useUrl, useLocaleStorage, useSessionStorage, useCookie }) => {
const [initialCountry, setInitialCountry] = useState(/* logic to check where to read from, for the initial state */);
}
在上面的示例中,我需要将这个简单的JS转换为Reaction-Style:
let initialCountry = 'uk'
if (useUrl) {
// read from URL and set it
} else if (useCookie) {
// read from cookie and set it
} else if (useSessionStorage) {
// read from session storage and set it
} else if (useLocaleStorage) {
// read from local storage and set it
}
我知道我可以创建一个简单的状态,然后使用useEffect
来初始化它.但这使得该州发生了多次变化.我不想这样.我希望initial state是使用复杂的逻辑创建的,而不是changed.