如何使用来自localStorage的数据渲染React组件?

时间:2018-07-20 17:02:00

标签: javascript jquery html reactjs

我正在构建一个React应用,其中React应用的许多内容都从localStorage提取。在运行应用程序时,与其使用数据库,不如使用数据库,首先要做的是用数据填充localStorage,然后使用localStorage的数据从JS构建HTML。...

但是现在有了React,我开始从对信息进行硬编码转变为从localStorage使用信息。但是,似乎React组件是在加载localStorage的JS之前呈现的。使用console.log,我发现React渲染首先完成。

在构建完JS的JS完成之后,我将如何确保未实现HTML(来自react组件)?

主要应用程序组件

class App extends React.Component {

  constructor(props) {
    super(props);
    console.log("Constructing App");
  }

  render() {
    return (
    <div>
      <Navigation {this.title: "Something based on localStorage"/>
     </div>
    )}
 }

导航组件

function Navigation(props) {
  console.log("Constructing Nav");

  return ("stuff here pulled from props like props.title")
}

3 个答案:

答案 0 :(得分:5)

您可以使用本地存储getItem method- localStorage.getItem('myData');

class App extends React.Component {

  constructor(props) {
    super(props);
    state: {
      myData: {}      
    }  
  }

  componentDidMount(){
    const myData = localStorage.getItem('myData');
    // set the state with the data
    this.setState({myData});
  }

  render() {
    return (
    <div>
      <Navigation title={this.state.myData} />
     </div>
    )}
 }

答案 1 :(得分:0)

让我尝试对您的代码进行一些修改:

class App extends React.Component {
      constructor(props) {
        super(props);
        console.log("Constructing App");
        this.state={
          fromLocal:''
        }
      }
      componentDidMount(){
        let newSearchColumns = localStorage.getItem('searchColumns');
        this.setState({fromLocal: newSearchColumns})
      }

      render() {
        return (
        <div>
          <Navigation title= {this.state.fromLocal}/>
         </div>
        )}
     }

您应该研究以下内容: Lifecycle methodsLocal Storage

答案 2 :(得分:0)

React Component的默认方法按特定顺序(the "lifecycle" of the component)运行。

如果您要执行某些操作(例如构建localStorage),则可以将它们放在顺序的前面。

初始化和挂载都在渲染之前进行,因此您可以在这两个阶段之一中构建localStorage。具体来说,请尝试重写componentWillMount()方法。

相关问题