【问题标题】:Table body not updating in react , when fetching data from firebase从firebase获取数据时,表体未在反应中更新
【发布时间】:2021-09-25 22:35:10
【问题描述】:

我正在从 firebase 获取一些数据并更新状态,但在页面加载时表格没有更新。无论如何,如果我对文件进行一些更改并保存它,表格就会更新。

代码-

  const [leaderdata, setdata] = useState({});
  const database = firebase.database().ref();

  useEffect(() => {
    var x = 0;
    //getting the data from firebase and storing it in a state
    database.orderByChild("ques_fund").once("child_added", (snapshot) => {
      var temp = leaderdata;
      temp[x] = snapshot.val();
      setdata(temp);
      x = x + 1;
    });
    console.log(leaderdata);
  }, []);


return (
    <div>
      <table>
        <thead>
          <tr>
            <th>Rank</th>
            <th>Participant Name</th>
            <th>Score</th>
          </tr>
        </thead>
        <tbody>
          {leaderdata ? (
            Object.values(leaderdata).map((row, index) => {
              console.log("hi");
              return (
                <tr key={row.timestamp}>
                  <td>{index}</td>
                  <td>{row.name}</td>
                  <td>{row.ques_fund}</td>
                </tr>
              );
            })
          ) : (
            <h1>No data</h1>
          )}
        </tbody>
      </table>
    </div>
  );

useEffect(即leaderdata)末尾的console.log给出-> log at the end of use Effect

【问题讨论】:

  • 能否请console.log(leaderdata)在你的useEffect结束时分享输出?
  • 嘿@Dharmaraj 我编辑了问题

标签: reactjs firebase firebase-realtime-database state react-table


【解决方案1】:

使用反应状态的一个规则是你不应该直接修改状态。

修改你的useEffect钩子为:

useEffect(() => {
  var x = 0;
  //getting the data from firebase and storing it in a state
  database.orderByChild("ques_fund").once("child_added", (snapshot) => {
    // var temp = leaderdata;
    // create another copy of state;
    var temp = {...leaderdata};
    temp[x] = snapshot.val();
    setdata(temp);
    x = x + 1;
  });
  console.log(leaderdata);
}, []);

在每个setState之后,react 比较状态是否发生了变化。对于对象(数组是一个对象),比较的是引用。当你改变一个对象时,引用不会被修改。

您可以使用此示例代码进行验证

const obj1 = {a: 1, b: 2, c: 3, d: 4};
const obj2 = obj1;  // use the original reference
const obj3 = {...obj1}; // created a new copy
obj1.a = 4;
obj3.a = 4;
console.log(obj1 === obj2); // true
console.log(obj1 === obj3); // false

你可以在官方React Docs阅读更多这样的规则

编辑:更改代码以使用对象。

另外,我意识到你也应该学习传播运算符。查看更多Spread Syntax | MDN

【讨论】:

  • 嘿,@Avinash 我明白你在说什么,但在我的情况下,leaderdata 状态是一个对象,而不是一个数组,所以通过做你所做的(使用 ...)我得到和错误,说 leaderdata不可迭代。
  • @Vedant Tewari,更新了答案。此外,您可以从我在答案中添加的链接中了解有关传播运算符的更多信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-06
  • 2021-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多