首先反应加载本地存储

ary*_*yan 5 reactjs redux

我有一个类似我的反应应用程序,App.js其中包括我HeadersFooters..

在这里,我将我的内容存储state到本地存储中。存储之后,我可以检索它..

但是我在加载它时遇到了问题。在浏览器中,localstorage['key']它可以为我提供数据,但无法加载。

我应该先在哪里加载?

我有Root.js

class Root extends Component {
  render() {
    const { store } = this.props
    return (
      <Provider store={store}>
          <ReduxRouter />
      </Provider>
    )
  }
}

Root.propTypes = {
  store: PropTypes.object.isRequired
}

export default Root
Run Code Online (Sandbox Code Playgroud)

index.js在外部级别:

const store = configureStore()


render(

    <Root store={store} />,
  document.getElementById('root')
)
Run Code Online (Sandbox Code Playgroud)

我应该在哪里装载我的localStorage

需要帮忙 。我需要知道在react中首先调用什么,以便我可以调用以加载到localStorage那里。

Spi*_*idi 0

我建议从componentDidMountapp.js 文件内的方法获取本地存储数据。

请在此处找到官方参考: https: //facebook.github.io/react/docs/component-specs.html#mounting-componentdidmount

如果您想在卸载组件之前更新 localStorage 数据,可以使用以下方法componentWillUnmount: https: //facebook.github.io/react/docs/component-specs.html#unmounting-componentwillunmount

  • 问题说“首先”,所以“componentDidMount”没有用。如果组件的生命周期必须使用,那就是“componentWillMount”,它比“componentDidMount”发生得更早。 (2认同)