我第一次尝试React钩子,一切似乎都很好,直到我意识到,当我获得数据并更新两个不同的状态变量(数据和加载标志)时,我的组件(数据表)被渲染了两次,即使两个对状态更新器的调用都发生在同一个函数中。这是我的api函数,它将两个变量返回给我的组件。

const getData = url => {

    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);

    useEffect(async () => {

        const test = await api.get('/people')

        if(test.ok){
            setLoading(false);
            setData(test.data.results);
        }

    }, []);

    return { data, loading };
};

在一个普通的类组件中,你只需要一次调用就可以更新一个复杂的对象的状态,但“钩子方式”似乎是将状态分割成更小的单元,其副作用似乎是当它们分别更新时需要多次重新渲染。有什么办法可以缓解这种情况吗?


当前回答

如果你正在使用第三方钩子,并且不能将状态合并到一个对象或使用useReducer,那么解决方案是使用:

ReactDOM.unstable_batchedUpdates(() => { ... })

此处由丹·阿布拉莫夫推荐

请看这个例子

其他回答

你可以将加载状态和数据状态合并到一个状态对象中,然后你可以做一个setState调用,只会有一个呈现。

注意:与类组件中的setState不同,useState返回的setState不会将对象与现有状态合并,它会完全替换对象。如果希望进行合并,则需要读取之前的状态,并自己将其与新值合并。参考文档。

在确定有性能问题之前,我不会太担心过度调用渲染。渲染(在React上下文中)和将虚拟DOM更新提交到真实DOM是不同的事情。这里的呈现指的是生成虚拟DOM,而不是更新浏览器DOM。React可以批处理setState调用,并使用最终的新状态更新浏览器DOM。

const {useState, useEffect} = React; function App() { const [userRequest, setUserRequest] = useState({ loading: false, user: null, }); useEffect(() => { // Note that this replaces the entire object and deletes user key! setUserRequest({ loading: true }); fetch('https://randomuser.me/api/') .then(results => results.json()) .then(data => { setUserRequest({ loading: false, user: data.results[0], }); }); }, []); const { loading, user } = userRequest; return ( <div> {loading && 'Loading...'} {user && user.name.first} </div> ); } ReactDOM.render(<App />, document.querySelector('#app')); <script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script> <div id="app"></div>

替代方案-编写自己的州合并钩子

const {useState, useEffect} = React; function useMergeState(initialState) { const [state, setState] = useState(initialState); const setMergedState = newState => setState(prevState => Object.assign({}, prevState, newState) ); return [state, setMergedState]; } function App() { const [userRequest, setUserRequest] = useMergeState({ loading: false, user: null, }); useEffect(() => { setUserRequest({ loading: true }); fetch('https://randomuser.me/api/') .then(results => results.json()) .then(data => { setUserRequest({ loading: false, user: data.results[0], }); }); }, []); const { loading, user } = userRequest; return ( <div> {loading && 'Loading...'} {user && user.name.first} </div> ); } ReactDOM.render(<App />, document.querySelector('#app')); <script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script> <div id="app"></div>

为了复制这个。setState类组件的合并行为, React文档建议使用useState的函数形式来扩展对象,不需要useReducer:

setState(prevState => {
  return {...prevState, loading, data};
});

这两个状态现在合并为一个,这将为您节省一个呈现周期。

使用一个状态对象还有另一个优点:加载和数据是相互依赖的状态。无效的状态变化变得更加明显,当把状态放在一起:

setState({ loading: true, data }); // ups... loading, but we already set data

你甚至可以通过以下方法更好地确保状态的一致性:1.)在你的状态中显式地显示状态——加载、成功、错误等;2.)使用useReducer在一个reducer中封装状态逻辑:

const useData = () => {
  const [state, dispatch] = useReducer(reducer, /*...*/);

  useEffect(() => {
    api.get('/people').then(test => {
      if (test.ok) dispatch(["success", test.data.results]);
    });
  }, []);
};

const reducer = (state, [status, payload]) => {
  if (status === "success") return { ...state, data: payload, status };
  // keep state consistent, e.g. reset data, if loading
  else if (status === "loading") return { ...state, data: undefined, status };
  return state;
};

const App = () => {
  const { data, status } = useData();
  return status === "loading" ? <div> Loading... </div> : (
    // success, display data 
  )
}

const useData = () => { const [state, dispatch] = useReducer(reducer, { data: undefined, status: "loading" }); useEffect(() => { fetchData_fakeApi().then(test => { if (test.ok) dispatch(["success", test.data.results]); }); }, []); return state; }; const reducer = (state, [status, payload]) => { if (status === "success") return { ...state, data: payload, status }; // e.g. make sure to reset data, when loading. else if (status === "loading") return { ...state, data: undefined, status }; else return state; }; const App = () => { const { data, status } = useData(); const count = useRenderCount(); const countStr = `Re-rendered ${count.current} times`; return status === "loading" ? ( <div> Loading (3 sec)... {countStr} </div> ) : ( <div> Finished. Data: {JSON.stringify(data)}, {countStr} </div> ); } // // helpers // const useRenderCount = () => { const renderCount = useRef(0); useEffect(() => { renderCount.current += 1; }); return renderCount; }; const fetchData_fakeApi = () => new Promise(resolve => setTimeout(() => resolve({ ok: true, data: { results: [1, 2, 3] } }), 3000) ); ReactDOM.render(<App />, document.getElementById("root")); <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script> <div id="root"></div> <script>var { useReducer, useEffect, useState, useRef } = React</script>

PS:请确保在自定义Hooks前加上use (useData而不是getData)。同时传递给useEffect的回调不能是异步的。

批处理更新在react-hooks https://github.com/facebook/react/issues/14259

React目前会批处理状态更新,如果它们是在一个基于React的事件中触发的,比如按钮点击或输入更改。如果它们是在React事件处理程序之外触发的,就像异步调用一样,它不会批量处理更新。

补充一点回答https://stackoverflow.com/a/53575023/121143

太酷了!对于那些计划使用这个钩子的人来说,它可以用一种有点健壮的方式来使用function作为参数,比如:

const useMergedState = initial => {
  const [state, setState] = React.useState(initial);
  const setMergedState = newState =>
    typeof newState == "function"
      ? setState(prevState => ({ ...prevState, ...newState(prevState) }))
      : setState(prevState => ({ ...prevState, ...newState }));
  return [state, setMergedState];
};

更新:优化版本,当传入的部分状态没有改变时,状态不会被修改。

const shallowPartialCompare = (obj, partialObj) =>
  Object.keys(partialObj).every(
    key =>
      obj.hasOwnProperty(key) &&
      obj[key] === partialObj[key]
  );

const useMergedState = initial => {
  const [state, setState] = React.useState(initial);
  const setMergedState = newIncomingState =>
    setState(prevState => {
      const newState =
        typeof newIncomingState == "function"
          ? newIncomingState(prevState)
          : newIncomingState;
      return shallowPartialCompare(prevState, newState)
        ? prevState
        : { ...prevState, ...newState };
    });
  return [state, setMergedState];
};

这样做:

const [state, setState] = useState({ username: '', password: ''});

// later
setState({
    ...state,
    username: 'John'
});