在使用SSR时初始化反应组件状态的最佳方法是什么?

问题描述 投票:-1回答:3

我正在构建一个表,状态需要在某处初始化,哪些数据最终通过fetch更新。

我的问题是表需要在服务器端呈现,因此在安装组件之前需要在服务器上呈现数据,我不能使用componentDidMount。

我可以使用props在render()方法中渲染表格内容,但是当表格不依赖于通过道具接收数据但是通过调用api时,如何更新数据呢?

我的结论是我必须使用状态,但初始化状态与道具似乎是一个很大的不,所以我在一个困境。

在不违反规则的情况下,您对初始化组件状态有何建议?

reactjs serverside-rendering react-props ssr react-state-management
3个回答
1
投票

我的意思是:让你的组件通过使用默认值初始化状态来挂载一个空表,并向你的组件添加一个函数,该函数从你所说的数据应该来自哪里取。当对您的应用程序有意义的事件发生时,可以调用此函数。

让我知道是否以及为什么不起作用,以及您遇到的其他问题。


1
投票

您可以使用props初始化状态。这没有问题。

我的方法是:

  • 保留一个状态变量并使用props初始化它以在服务器端呈现它。
  • 当组件安装在客户端时,API将在componentDidMount中调用。
  • 将在componentWillReceiveProps或静态getDerivedStateFromProps中监视任何新的道具更改(取决于您的反应版本)。如果有任何新数据,请更新redux-store(如果您使用的是redux-store)或更新组件状态以使重新呈现显示更新的数据。

锅炉板示例:

class Component1 extends React.Component{
  constructor(props) {
    super(props)
    this.state = {
      tableData: props.tableData
    }
  }

  componentDidMount() {
    //Make API call here
    callAPItoGetData()
  }

  componentWillReceiveProps(nextProps) {
    const { tableData } =  nextProps
    if(tableData !== this.state.tableData ) { 
      //You need to make sure that this condition is fullfiled only once to avoid setting state multiple times
      this.setState({
        tableData: nextProps.tableData
      })
      //Alternatively, an action can be dispatched to update the redux-store which will update the props and cause re-render with new data
    }
  }

  render() {
    return (
      <div>{/*render table here*/}</div>
    )
  }
}

希望能帮助到你。回复任何疑惑/困惑。


1
投票

对于React Hooks和useEffect钩子来说,这将是一个很好的例子。根据文件:

您可以将useEffect Hook视为componentDidMount,componentDidUpdate和componentWillUnmount的组合。

下面是一个简单的示例,其中组件首先将prop数据作为状态,但是一旦API调用完成,它就会更改为API数据:

import React, { useState, useEffect } from "react";

function DataList(props) {
  const [users, setUsers] = useState(props.propData);
  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then(res => res.json())
      .then(data => {
        setUsers(data);
      });
  });
  return (
    <ul>
      {users.map((user, index) => (
        <li key={index}>{user.name}</li>
      ))}
    </ul>
  );
}

export default DataList;
© www.soinside.com 2019 - 2024. All rights reserved.