![](/img/trans.png)
[英]how can i set initial value for usestate from redux state using selector in react native?
[英]how can we use redux state in useState to set initial values
我正在嘗試使用 redux 值來設置使用 useState 的 react 組件的初始狀態。當我嘗試設置 setIsStar 的狀態時,它說 currentChannelName 為 null。 我怎樣才能避免這種情況? 或者有沒有其他方法
const currentChannel = useSelector(state => state.channel.currentChannel);
const currentChannelName = currentChannel.name;
const [isStar, setIsStar] = useState({
[currentChannelName]: true
});
可能的解決方案是將它與useEffect
結合起來:
const currentChannel = useSelector(state => state.channel.currentChannel);
const currentChannelName = currentChannel.name;
useEffect(() => {
if(currentChannelName) {
setIsStar({[currentChannelName]: true});
}
}, [currentChannelName]); // listen only to currentChannelName changes
const [isStar, setIsStar] = useState(currentChannelName ? {
[currentChannelName]: true
}: {});
`
您應該避免這種情況,因為它會在兩個不同的域中稀釋您的狀態。
在您的 redux 存儲中保持應用程序范圍的狀態,在您的組件中保持本地組件狀態。
如果您真的想這樣做,您可能只需要處理您的組件已安裝但存儲未填充您需要的數據的初始情況。
const currentChannel = useSelector(state => state.channel.currentChannel);
const currentChannelName = currentChannel.name;
const [isStar, setIsStar] = useState(currentChannelName && {
[currentChannelName]: true
});
最簡單的解決方案是:
// Redux state
const user = useSelector((state) => state.user);
const [firstName, setFirstName] = useState(user.firstName || '');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.