带有钩子的反应上下文防止重新渲染

React context with hooks prevent re render

我使用带有钩子的 React 上下文作为我的 React 应用程序的状态管理器。每次商店中的值发生变化时,所有组件都会重新渲染。

有什么方法可以防止 React 组件重新渲染吗?

商店配置:

import React, { useReducer } from "react";
import rootReducer from "./reducers/rootReducer";

export const ApiContext = React.createContext();

export const Provider = ({ children }) => {
  const [state, dispatch] = useReducer(rootReducer, {});

  return (
    <ApiContext.Provider value={{ ...state, dispatch }}>
      {children}
    </ApiContext.Provider>
  );
};

一个reducer的例子:

import * as types from "./../actionTypes";

const initialState = {
  fetchedBooks: null
};

const bookReducer = (state = initialState, action) => {
  switch (action.type) {
    case types.GET_BOOKS:
      return { ...state, fetchedBooks: action.payload };

    default:
      return state;
  }
};

export default bookReducer;

根减速器,可以组合尽可能多的减速器:

import userReducer from "./userReducer";
import bookReducer from "./bookReducer";

const rootReducer = ({ users, books }, action) => ({
  users: userReducer(users, action),
  books: bookReducer(books, action)
});

动作示例:

import * as types from "../actionTypes";

export const getBooks = async dispatch => {
  const response = await fetch("https://jsonplaceholder.typicode.com/todos/1", {
    method: "GET"
  });

  const payload = await response.json();

  dispatch({
    type: types.GET_BOOKS,
    payload
  });
};
export default rootReducer;

这是本书的组成部分:

import React, { useContext, useEffect } from "react";
import { ApiContext } from "../../store/StoreProvider";
import { getBooks } from "../../store/actions/bookActions";

const Books = () => {
  const { dispatch, books } = useContext(ApiContext);
  const contextValue = useContext(ApiContext);

  useEffect(() => {
    setTimeout(() => {
      getBooks(dispatch);
    }, 1000);
  }, [dispatch]);

  console.log(contextValue);

  return (
    <ApiContext.Consumer>
      {value =>
        value.books ? (
          <div>
            {value.books &&
              value.books.fetchedBooks &&
              value.books.fetchedBooks.title}
          </div>
        ) : (
          <div>Loading...</div>
        )
      }
    </ApiContext.Consumer>
  );
};

export default Books;

当 Books 组件中的值发生变化时,另一个我的组件 Users 重新渲染:

import React, { useContext, useEffect } from "react";
import { ApiContext } from "../../store/StoreProvider";
import { getUsers } from "../../store/actions/userActions";

const Users = () => {
  const { dispatch, users } = useContext(ApiContext);
  const contextValue = useContext(ApiContext);

  useEffect(() => {
    getUsers(true, dispatch);
  }, [dispatch]);

  console.log(contextValue, "Value from store");

  return <div>Users</div>;
};

export default Users;

优化上下文重新呈现的最佳方法是什么?提前致谢!

我试着用不同的例子来解释希望能有所帮助。

因为上下文使用引用标识来确定何时 re-render,当提供者的父级 re-render 时,这可能会触发消费者的无意渲染。

例如:下面的代码将 re-render 所有消费者每次 Provider re-renders 因为总是为 value

创建一个新对象
class App extends React.Component {
  render() {
   return (
      <Provider value={{something: 'something'}}>
        <Toolbar />
      </Provider>
    );
 }
}

为了解决这个问题,将值提升到父级的状态

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: {something: 'something'},
    };
  }

  render() {
    return (
      <Provider value={this.state.value}>
        <Toolbar />
      </Provider>
    );
  }
}

此解决方案用于防止组件在 React 中呈现,称为 shouldComponentUpdate。它是一种生命周期方法,可用于 React class 组件。而不是像以前那样将 Square 作为功能性无状态组件:

const Square = ({ number }) => <Item>{number * number}</Item>;

您可以将 class 组件与 componentShouldUpdate 方法一起使用:

class Square extends Component {
  shouldComponentUpdate(nextProps, nextState) {
    ...
  }

  render() {
    return <Item>{this.props.number * this.props.number}</Item>;
  }
}

如您所见,shouldComponentUpdate class 方法可以访问组件的 运行 re-rendering 之前的下一个道具和状态。这就是您可以决定通过此方法的 returning false 来阻止 re-render 的地方。如果 return 为真,组件 re-renders.

class Square extends Component {
  shouldComponentUpdate(nextProps, nextState) {
    if (this.props.number === nextProps.number) {
      return false;
    } else {
      return true;
    }
  }

  render() {
    return <Item>{this.props.number * this.props.number}</Item>;
  }
}

在这种情况下,如果传入号码属性没有改变,组件不应该更新。通过再次将控制台日志添加到您的组件来亲自尝试。 Square 组件不应该在视角改变时重新渲染。这对你的 React 应用程序来说是一个巨大的性能提升,因为你的所有子组件都不会随着它们父组件的每次重新渲染而重新渲染。最后,防止组件重新渲染取决于您。

了解了这个componentShouldUpdate方法一定能帮到你!

我相信这里发生的是预期的行为。它呈现两次的原因是当您分别访问图书或用户页面时,您会自动抓取一个新的 book/user。

发生这种情况是因为页面加载,然后 useEffect 启动并抓取图书或用户,然后页面需要 re-render 以便将新抓取的图书或用户放入 DOM.

我已经修改了你的 CodePen 以证明是这种情况。如果你在书籍或用户页面上禁用 'autoload'(我为此添加了一个按钮),然后浏览该页面,然后浏览回那个页面,你会看到它只呈现一次。

我还添加了一个按钮,允许您按需获取新书或用户...这是为了显示如何只有您所在的页面得到 re-rendered。

总而言之,据我所知,这是预期的行为。

BooksUsers 目前在每个周期 重新渲染 - 不仅在存储值更改的情况下。

1。道具和状态变化

React re-renders the whole sub component tree 以组件作为根开始,其中 props 或状态发生了变化。您通过 getUsers 更改父状态,因此 BooksUsers 重新渲染。

const App = () => {
  const [state, dispatch] = React.useReducer(
    state => ({
      count: state.count + 1
    }),
    { count: 0 }
  );

  return (
    <div>
      <Child />
      <button onClick={dispatch}>Increment</button>
      <p>
        Click the button! Child will be re-rendered on every state change, while
        not receiving any props (see console.log).
      </p>
    </div>
  );
}

const Child = () => {
  console.log("render Child");
  return "Hello Child ";
};


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>

优化技术

使用 React.memo 来防止重新渲染一个 comp,如果它自己的道具实际上没有改变的话。

// prevents Child re-render, when the button in above snippet is clicked
const Child = React.memo(() => {
  return "Hello Child ";
});
// equivalent to `PureComponent` or custom `shouldComponentUpdate` of class comps

重要提示: React.memo 仅检查道具更改(useContext 值更改触发重新渲染)!


2。上下文变化

All 上下文消费者 (useContext) 在上下文值更改时自动重新呈现。

// here object reference is always a new object literal = re-render every cycle
<ApiContext.Provider value={{ ...state, dispatch }}>
  {children}
</ApiContext.Provider>

优化技术

确保上下文值有稳定的对象引用,例如通过 useMemo 钩子。

const [state, dispatch] = useReducer(rootReducer, {});
const store = React.useMemo(() => ({ state, dispatch }), [state])

<ApiContext.Provider value={store}>
  {children}
</ApiContext.Provider>

其他

不确定,为什么你把所有这些构造放在Books中,只用一个useContext:

const { dispatch, books } = useContext(ApiContext);
// drop these
const contextValue = useContext(ApiContext); 
<ApiContext.Consumer> /* ... */ </ApiContext.Consumer>; 

您还可以使用 React.memouseContext 查看