简体   繁体   中英

How i can change UI on change redux-toolkit state?

I want to rerender my component when i'm dispatch from another component, how i can do it?

Component that need for rerender:

const MessageComponent = (): JSX.Element => {
    const [messages, setMessages] = useState<IMessageComponentState>({
        messages: []
    })

    const message = useSelector((state: RootState) => state.message.messages);

    useEffect(() => {
        setMessages({
            messages: message
        })
        console.log(message)
    }, message);



    return (
        <>
            {messages.messages}
            <MyMessageComponent  message="some text"/>
            <IncomeMessageComponent  message="some text2"/>
        </>

    )
}

This will cause re-render.

If you need more to re-render, like the <MyMessageComponent /> or the `, they'd just need to have some form of conditional rendering attached to the message variable or use it.

The primary value of post-react-hooks redux is the rendering, or rather, the lack thereof; it only re-renders what it absolutely has to, ie, components that require the change directly.

Dependency in useEffect have to put inside [ ] . See more: Conditionally firing an effect .

And messages state is an array but you set a object, change from setMessages({ messages: message }) to setMessages((mes) => [...mes, {messages: message}])

const MessageComponent = (): JSX.Element => {
    const [messages, setMessages] = useState<IMessageComponentState>({
        messages: []
    })

    const message = useSelector((state: RootState) => state.message.messages);

    useEffect(() => {
        setMessages((mes) => [...mes, {
            messages: message
        }])
        console.log(message)
    }, [message]); //<=== Put message in []



    return (
        <>
            {messages.messages}
            <MyMessageComponent  message="some text"/>
            <IncomeMessageComponent  message="some text2"/>
        </>

    )
}

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