【问题标题】:How to Render React Components with Data from localStorage?如何使用 localStorage 中的数据渲染 React 组件?
【发布时间】:2018-07-21 01:23:51
【问题描述】:

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

但是现在有了 React,我开始从硬编码信息转移到从 localStorage 中使用它。但是,似乎反应组件是在加载 localStorage 的 JS 之前呈现的。使用 console.log,我发现 React 渲染是在其他任何事情之前完成的。在构建 localStorage 的 JS 完成之前,我将如何确保不实现 HTML(来自反应组件)?

主要应用组件

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")
}

【问题讨论】:

    标签: javascript jquery html reactjs


    【解决方案1】:

    你可以使用本地存储getItemmethod - 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>
        )}
     }
    

    【讨论】:

    • 这根本不能解决问题。这将获取本地存储。但问题是,这会在我的 JQuery 填充之前获得 localStorage。我需要 React 在存储填充后加载组件
    • 您的帖子中的jQuery 在哪里?这是你第一次提到它,jQuerylocalStorage 有什么关系?
    • @user10059818 你从来没有在你的问题中提到jQuery
    • @user10059818 无论如何,如果您在安装组件之前需要数据,您可以在constructor 方法中完成。
    • 我可以调用我的“loadMyDataInStorage()”函数但是,由于异步,React 将在调用该函数后继续渲染其他所有内容....这意味着所有内容仍然在 LoadMyDatainStorage( ) 函数完成。
    【解决方案2】:

    让我试着修改你的代码:

    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

    【讨论】:

      【解决方案3】:

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

      如果您有想要执行的操作,例如构建 localStorage,您可以将它们放在序列的前面。

      初始化和挂载都发生在渲染之前,因此您可以在任一阶段构建 localStorage。具体来说,尝试覆盖 componentWillMount() 方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-06
        • 1970-01-01
        • 2018-01-11
        • 1970-01-01
        • 1970-01-01
        • 2018-12-24
        相关资源
        最近更新 更多