Реагируйте на значения обновления контекста с помощью Context.Consumer, но не с contextType - PullRequest
0 голосов
/ 01 октября 2019

Я пытался использовать контекст React в компоненте React, но у меня возникли некоторые проблемы.

В моем Component.jsx у меня есть такой метод рендеринга:

render() {
    return (
      <NavigationProvider>
        <ShipmentsContext.Consumer>
          {({ isDetailsVisible }) => (
            <div>
              {this.renderHeader(isDetailsVisible)}
            </div>
          )}
        </ShipmentsContext.Consumer>
      </NavigationProvider>
    );
  }

Это работает хорошо, и isDetailsVisible обновляется как я хочу.

Но я хочу удалить <ShipmentsContext.Consumer> и использовать contextType, но когда я получаю isDetailsVisible в моем методе renderHeader, он всегда устанавливается наfalse и без обновления ...

Вот код renderHeader

  • Использование <ShipmentsContext.Consumer>: (isDetailsVisible обновляется)
renderHeader(isDetailsVisible) {
    const { classes } = this.props;

    return (
      <Searchbar className={classNames({ [classes.nodeTranslated]: isDetailsVisible})}/>
    );
  }
  • Использование contextType: (isDetailsVisible is NOT update => всегда установлено значение по умолчанию)
renderHeader() {
    const { classes } = this.props;
    const { isDetailsVisible } = this.context;

    return (
      <Searchbar className={classNames({ [classes.nodeTranslated]: isDetailsVisible })}/>
    );
  }

Любая идея? Спасибо!

1 Ответ

0 голосов
/ 01 октября 2019

Предполагая, что у вас неприятный контекст ShipmentsContext, вы случайно пропускаете соответствующий ShipmentsContext.Provider?

Вы сбрасываете <ShipmentsContext.Consumer> и сохраняете <ShipmentsContext.Provider>. Потребитель контекста может быть установлен с помощью contextType в качестве поля статического класса:

class MyComp extends React.Component {
  static contextType = ShipmentsContext;
  ...
}

// When you don't want to/cannot use public class 
// fields syntax, this is the alternative:
// MyComp.contextType = ShipmentsContext;

Вот простой пример теста:

const ShipmentsContext = React.createContext({
  isDetailsVisible: "false from default"
});

class MyComp extends React.Component {
  static contextType = ShipmentsContext;

  render() {
    return this.renderHeader();
  }

  renderHeader() {
    return <p>{JSON.stringify(this.context)}</p>;
  }
}

const App = () => {
  // state realized with React Hooks. You could also use a 
  // class component and `setState` for App
  const [contextValue, setContextValue] = React.useState({
    isDetailsVisible: "true from Provider"
  });

  return (
    <ShipmentsContext.Provider value={contextValue}>
      <button
        onClick={() =>
          setContextValue({ isDetailsVisible: "UPDATED true from Provider" })
        }
      >
        Update Context
      </button>
      <MyComp />
    </ShipmentsContext.Provider>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.10.1/umd/react.production.min.js" integrity="sha256-vMEjoeSlzpWvres5mDlxmSKxx6jAmDNY4zCt712YCI0=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.10.1/umd/react-dom.production.min.js" integrity="sha256-QQt6MpTdAD0DiPLhqhzVyPs1flIdstR4/R7x4GqCvZ4=" crossorigin="anonymous"></script>

<div id="root"></div>

При нажатии на кнопку «Обновить контекст» контексту будет предоставлено новое значение, и renderHeader также получит уведомление об изменении.

Дайте мне знать, если это соответствует вашему делу. Удачи!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...