防止在上下文更改时重新加载组件(反应)

时间:2020-07-14 05:32:33

标签: javascript reactjs react-context

我有一个导入和使用CONTEXT的组件。在此组件中,我基于链接道具从CONTEXT渲染数据。到目前为止,一切都很好,但是在同一个组件中,我需要具有更新CONTEXT的能力,这意味着删除我实际在该组件中使用的数据。这当然会导致错误,因为由于上下文更改,组件正在刷新。

有人知道如何防止在CONTEXT更改时重新加载组件吗?

...other imports...
import AllWarriorsContext from '../../contexts/AllWariorsContext';


export default function WarriorPage() {
    let { identy } = useParams(); 
    const [myWarriorsListContext, setMyWarriorsListContext] = useContext(AllWarriorsContext);
    const {number} = myWarriorsListContext.find((e) => e.number === identy)); //destructuring from one of the context object

const deleteMe = () => {
    setMyWarriorsListContext((myWarriorsListContext) => {
            return myWarriorsListContext.filter((e) => {
                return e.number !== identy;
            });
        });
}

    return(
        <>
            <button
                onClick={deleteMe} // after click of course i got an error
            >
                 delete
            </button>
        </>
    );

}

1 个答案:

答案 0 :(得分:0)

回答“如何防止在CONTEXT更改时重新加载组件?” 将您的功能组件重写为类组件。然后,您可以将道具传递到组件,并使用shouldComponentUpdate手动强制在道具更改时不更新该组件。并且不要在该组件中使用useContext或contextType。下面是一个简单的示例:

    import React, { useState, useContext, createContext } from "react";

    const ThemeContext = createContext();

    const themes = {
        dark: {
            color: "white",
            backgroundColor: "rgb(21, 21, 21)"
        },
        light: {
            color: "rgb(21, 21, 21)",
            backgroundColor: "white"
        }
    };

    class Button extends React.Component {
        shouldComponentUpdate(nextProps, nextState) {
            if (this.props.theme !== nextProps.theme) {
            return false;
            }

            return true;
        }
        render() {
            const { toggleTheme, theme } = this.props;
            console.log("render");
            return (
            <button onClick={toggleTheme} style={themes[theme]}>
                Button
            </button>
            );
        }
    }
    const ThemeButton = () => {
        const { theme, toggleTheme } = useContext(ThemeContext);
        return <Button theme={theme} toggleTheme={toggleTheme} />;
    };

    function App() {
        const [theme, setTheme] = useState("light");
        const toggleTheme = () => {
            if (theme === "dark") setTheme("light");
            if (theme === "light") setTheme("dark");
        };
    return (
        <>
        <ThemeContext.Provider value={{ theme, toggleTheme }}>
            <ThemeButton />
        </ThemeContext.Provider>
        </>
    );
    }

    export default App;