简体   繁体   English

为什么 useEffect 挂钩在上下文中不适用于 state 变量?

[英]Why the useEffect hook does not work with state variable in context?

My code is here .我的代码在这里

I expect the content of the array testingData should be shown.我希望应该显示数组testingData的内容。

However, it does not be shown.但是,它没有显示出来。

When I remove the useEffect hook, it works.当我删除useEffect挂钩时,它可以工作。

Would you tell me why and how can I fix it?你能告诉我为什么以及如何解决它吗?

In react, a component only renders if there are any state or prop changes.在反应中,组件仅在有任何 state 或 prop 更改时才会呈现。 In your codebase rowList is a variable instead of a state.在您的代码库中, rowList是一个变量,而不是 state。 if you convert it to state, it should work.如果将其转换为 state,它应该可以工作。

import React, { useContext, useEffect, useState } from "react";
import WebContext from "./WebContext";
export default function QQTableBody(props) {
  let { testingData, setTestingData } = useContext(WebContext);
  const [rowList, setRowList] = useState([]);
  // let rowList=[];
  useEffect(() => {
    const list = [];
    testingData.forEach(data => {
      list.push(
        <tr>
         <td>{data}</td>
        </tr>
     );
   });
    setRowList(list);
   }, [testingData]);
 
   return <tbody>{rowList}</tbody>;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM