Explicitly Passing The Store Down

现在我们的结构上暂时没有什么问题了,在具体的细节里,我们的所有Container是通过全局变量的形式接触到store,并且从自身开始向下传递,我们先让他通过TodoApp传递进去,我们不再创建多余的全局变量,而是直接调用createStore,让Container通过属性的形式接触store :

ReactDOM.render(
  <TodoApp store={createStore(todoApp)} />,  // todoApp is combined reducers
  document.getElementById('root')
)

现在我们要做的修改无非是:

  • 给所有的Contianer加上store属性
const TodoApp = ({ store }) => (
  <div>
    <AddTodo store={store} />
    <VisibleTodoList store={store} />
    <Footer store={store} />
  </div>
)
  • 改变它们内部的引用方式:
const TodoApp = ({ store }) => (  // add props
  <div>
    <AddTodo store={store} />
    <VisibleTodoList store={store} />
    <Footer store={store} />
  </div>
)
const AddTodo = ({ store }) => {
 // ...
}
const Footer = ({ store }) => (  // add props
  <p>
    Show:
    {' '}
    <FilterLink
      filter='SHOW_ALL'
      store={store} //add props
    >
      All
    </FilterLink>

    ... 

  </p>
);
// In VisibileToDoList and FilterLink
componentDidMount() {
  const { store } = this.props // props will include {store}
  this.unsubscribe = store.subscribe(() =>
    this.forceUpdate()
  );
}

render() {
  const props = this.props
  const { store } = props
  const state = store.getState()  // store here is no longer the global variable

  return (
    <TodoList ... />
  )
}

以上

我们通过向Container显式传递store的方法避免了暴露全局变量,之后我们将会使用更为优雅的隐式传递。

results matching ""

    No results matching ""