【问题标题】:React state not updated and error "Can't perform a React state update on an unmounted component"React 状态未更新和错误“无法对未安装的组件执行 React 状态更新”
【发布时间】:2023-02-11 00:16:27
【问题描述】:

我正在尝试创建一个应用程序,一旦用户登录(输入 partyID),它会将他们定向到一个新页面,在该页面上它会拉回所有用户数据。一旦他们“登录”;新页面没有像我预期的那样提取数据。

但是,当我写入控制台时,数据显示为未定义,但当我在浏览器本地访问它时,获取 URL 确实有效。

enter image description here

这是我的代码

class CalcForm extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        data: [],
    };
}

 componentDidMount() {
    this.setState({ isLoading: true });
    const serachByCustomerId = this.props.location.state;
    const url =
        "<MYURL>/api/Customer/" +
        serachByCustomerId;

    console.log("URL Being used ", url);
    fetch(url)
        .then((res) => res.json())
        .then((data) => this.setState({ data: data }))

    if (!this.state.isLoading) {
        console.log("data after search", this.state.data);
    }
}

// renders to display on page
render() {
    const { data, isLoading } = this.state;
    // if page is loading displays loading text and spinner to make user awear
    if (isLoading) {
        return (
            <div className="pageLoading">
                <p>Loading...</p>
                <FadeLoader size={150} color={"#2d8259"} loading={isLoading} />
            </div>
        );
    }

    return (
        <div> hi </div>
    );
}

}
export default CalcForm;

我期望返回的数据被打印到控制台中,但在查看时我得到了 undefined 并且还有一个我不明白的错误

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    为什么不采用钩子方法呢?它更好,更容易做事:

    伪代码让你去。它有一个等待功能,所以你应该能够在你传入你的 url 后派生你的数据。

    export default function CalcForm() {
      const [isLoading, setLoading] = React.useState(true);
      const [data, setData] = React.useState(false);
    
      const getData = async () => {
        setLoading(true);
        const response = await fetch(url);
        setData(response.json());
        setLoading(false);
      };
    
      React.useEffect(() => {
        getData();
      }, []);
    
      if (isLoading) {
        return (
          <div className="pageLoading">
            <p>Loading...</p>
            <FadeLoader size={150} color="#2d8259" loading={isLoading} />
          </div>
        );
      }
      return <div className="pageLoading">hi</div>;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-07-01
      • 2020-11-21
      • 2020-08-04
      • 1970-01-01
      • 2019-11-09
      • 2019-05-30
      • 2021-05-30
      相关资源
      最近更新 更多