【问题标题】:React - fetching the data before the render (best solution)React - 在渲染之前获取数据(最佳解决方案)
【发布时间】:2018-09-08 07:14:29
【问题描述】:

所以,我有一个应用程序,用户可以在其中选择多个设置。比如数字格式或默认显示的货币。

为此,我有一个特殊的 API 端点 /settings 从中获取值。

当用户重新加载页面时,整个应用程序在服务器端呈现。我尽快触发设置获取(在顶级组件的componentWillMount 中),但有时会出现闪烁/延迟。

可能的解决方案:

  1. 第一个解决方案是在用户第一次加载应用程序时获取设置,并将其保存在localStorage(如果可用)中。缺点是第一次加载应用时,数字/货币仍可能与设置中的不同。

  2. 第二种解决方案是在应用程序在服务器端呈现之前获取数据,并将此数据注入到脚本标记的某个位置(如window.userSettings = { ...settings })。它可能会稍微延长重新加载加载时间,但设置将按照用户设置。

对于这样的问题还有其他解决方案吗?最好的方法是什么?

【问题讨论】:

  • localStorage 解决方案可能是合适的,但不适用于用户第一次访问您的应用程序。因此,我建议将您的状态设置为componentWillMount ,并使用默认状态来获取存储中的数据。一旦我将请求放在componentDidMount 中,它将避免闪烁延迟

标签: javascript node.js reactjs serverside-javascript


【解决方案1】:

我希望,这个解决方案可以帮助你。

步骤 1:在 componentWillMount 中执行 API 调用并检查错误。为currencies 分配两个状态,为error 分配一个状态,如果可能,为loading 分配另一个状态 第 2 步:使用您在componnetDidMount 中的状态分配localStorage 第 3 步:然后,在您的渲染方法下,检查 error statelocalStorage

下面给出的示例 sn-p

class App extends Component{

  custructor(props){
    super(props);
    this.state={
      currency_number: '',
      error: false
    }
  }

  componentWillMount(){
    //perform fetch api and assign the state with the received items
    // check for error, if so then setState({error: true})
  }

  ComponentDidMount(){
    localStorage.setItem('currency', JSON.stringify(this.state.currency_number))
  }

  render(){
    const currency =  JSON.parse(localStorage.getItem('currency'))
    if (this.state.error) {
      return(
        <div>
          { currency }
        </div>

      )
    }
  }
}

【讨论】:

  • 谢谢,但并没有解决我在加载应用时没有设置的问题
猜你喜欢
  • 1970-01-01
  • 2021-05-11
  • 1970-01-01
  • 1970-01-01
  • 2021-04-17
  • 2019-08-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-31
相关资源
最近更新 更多