首页 > 解决方案 > 如果从反应钩子中的许多来源获取,如何防止重新渲染?

问题描述

react hooks在 React Native 中使用。我的问题是useState初始化状态的函数会重新渲染。所以如果我设置如下状态

    const [A, setA] = useState(false);
    const [B, setB] = useState(false);
    const [C, setA] = useState(false);

    // ...

    const testFunc = () => {
        setA(true);
        setB(true);
        setC(true);
    }


编辑 我认为例子是错误的。这是另一个例子。

const useFetch(coords) {
    const [example, setExample] = useState([])
    const [checker, setChecker] = useState(false);

    const fetchData = () => {
        axios.fetch(`url+${coords.latitue}+${coords.longitude}`).then(){
            setExample(res.data());
            setChecker(true);
        }
    }

    useEffect(() => {
        fetchData();
    }, [coords])

    return example;
}

const useLocation = () => {
    ...
    return coords;
}

const App = () => {
    const coords = useLocation();
    const example = useFetch(coords); // example is undefined.
    const [data, setData] = useState(example); // data is undefined.
}

它会导致与我使用 set 函数一样多的重新渲染。这是自然现象吗?如果我不想重新渲染,不能多次使用 set 函数吗?

标签: reactjsreact-hooks

解决方案


你不能以直接的方式做到这一点。我会为你推荐两种解决方案。

解决方案 1:在一个对象中组合状态。

const [value, setValue] = useState({A: false, B: false, C: false});

// ...

const testFunc = () => {
    setValue({A: true, B: true, C: true});
}

解决方案 2:另一种解决方案是useReducer.

const [state, setState] = useReducer(
  (state, newState) => ({...state, ...newState}),
  {A: false, B: false, C: false}
);

// ...

const testFunc = () => {
    setState({A: true, B: true, C: true});
}

在这里,我实现了您的另一个示例:https ://stackblitz.com/edit/react-usestate-wcjshg

希望这对你有帮助!


推荐阅读