简体   繁体   中英

how can we use redux state in useState to set initial values

I am trying to use redux value to set an initial state of react component using useState.when I am trying to set the state of setIsStar it says currentChannelName is null. How can I avoid this? or is there any other way

const currentChannel = useSelector(state => state.channel.currentChannel);
   const currentChannelName = currentChannel.name;


  const [isStar, setIsStar] = useState({
    [currentChannelName]: true
  });

Possible solution is to combine it with 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
}: {});

`

You should avoid this as it dilutes your state across two separate domains.

Keep app-wide state in your redux store, keep local component state in your components.

If you really do want to do this, you'll probably just have to deal with the initial case where your component has mounted but the store is not populated with the data you need.

const currentChannel = useSelector(state => state.channel.currentChannel);
const currentChannelName = currentChannel.name;

const [isStar, setIsStar] = useState(currentChannelName && {
  [currentChannelName]: true
});

The easiest solution would be:

// Redux state
const user = useSelector((state) => state.user);

const [firstName, setFirstName] = useState(user.firstName || '');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM