如果据说 Provider 已经将所有道具传递给所有 children,那么注入装饰器有什么意义?

What's the point of inject decorator if Provider is said to be already passing all the props down to all the children?

考虑一个案例:

import { Provider } from 'mobx-react';
import usersStore from './stores/usersStore';
import itemsStore from './stores/itemsStore';

const stores = { usersStore, itemsStore };

ReactDOM.render(
  <Provider {...stores}>
    <SomeComponent />
  </Provider>,
  document.getElementById('app')
);

那么,上面示例中的 SomeComponent 是否已经从 Provider 中获得了 usersStoreitemsStore 作为其 props?为什么甚至需要以下示例中的 @inject('itemsStore') 行?

@inject('itemsStore') @observer
class SomeComponent extends React.Component {
  render() {
    return (
      <div className="index">
        {this.props.itemsStore.items.map((item, index) => {
          return <span key={index}>item.name</span>
        })}
      </div>
    );
  }
}

Provider is a component that can pass stores (or other stuff) using React's context mechanism to child components. This is useful if you have things that you don't want to pass through multiple layers of components explicitly.

inject can be used to pick up those stores. It is a higher order component that takes a list of strings and makes those stores available to the wrapped component.

Providerinject 是对 React context API 的抽象(直到最近还很不稳定)。

Provider 使组件上下文中的数据可用,而 inject HOC 提供了一个简单的 API 来声明我们想要从上下文中获取的内容并将其传递给包装器组件。

同样适用于其他库,例如 react-redux