不重新渲染反应(已解决)

问题描述 投票:0回答:4

我今天正在从事React组件的工作,以前曾经在其中工作过,但是在涉及到它时,我仍然觉得自己很不错。

问题:我的setState正在刷新和更改this.state,但是我的组件根本没有重新呈现。我可以观看状态更改,甚至可以手动更改状态,但是它仍然不会更改任何条件渲染。我正在尝试有条件地渲染ProcessingBox和JobsGrid,但是我什么也无法加载。

尝试:我试图对组件周围的所有日志进行控制台,甚至在函数中,我都获得了想要的正确输出,但不会重新加载组件。我也尝试过进行forceUpdate,但是仍然无法正常工作。 Aslo尝试使componentDidMount异步,但是没有运气。我的下一个理论与样式化组件有关,还有npm可能遗漏的某些东西。

import React, { Component } from 'react';
import { render } from 'react-dom';
import { JobsGrid, ProcessingBox, JobsContainer } from './styled';

class Employment extends Component {
  state = {
    categories: [],
    jobs: [],
    activeJob: {},
    activeCategory: {},
    processing: false
  };


  componentDidMount() {
    this.getCategories();
  }

  getCategories = async () => {
    this.setState({ processing: true });
    await fetch('url', {
      headers: {
        Authorization: 'Bearer token',
      }
    }).then(res => res.json())
      .then((result) => {
        this.setState({ categories: result.data, processing: false });
      });
  };

  isLoading = (processing) => {
    console.log(processing);
    if (processing) {
      return (
        <ProcessingBox>
          <img src="/build/img/loading.GIF" alt="" />
        </ProcessingBox>
      )
    } else {
      return (
        <JobsGrid>
          <div className="container">
            <div>Hi</div>
          </div>
        </JobsGrid>
      )
    }
  };


  render() {

    return (
      <JobsContainer>
        {
          this.isLoading(this.state.processing)
        }
      </JobsContainer>
    );
  }
}

const
  element = document.querySelector('#employment');

if (element) {
  render(
    <Employment />,
    element
  );
}

解决方案:错误的依赖关系。整个时间都正确。感谢您的帮助!

javascript reactjs
4个回答
0
投票

尝试以此更改您的getCategories函数,

getCategories = async () => {
 this.setState({ processing: true });
 const res = await fetch('url', { headers: { Authorization: 'Bearer token',} });
 const result = await res.json();
 this.setState({ categories: result.data, processing: false });
};

我认为您正在使用并且同时等待,等待用于等待诺言,看它是否解决了您的问题,

希望有帮助


0
投票

您需要在抓取中添加.catch

getCategories = async () => {
    this.setState({ processing: true });
    await fetch('url', {
    headers: {
        Authorization: 'Bearer token',
    }
    })
        .then(res => res.json())
        .then((result) => {
            this.setState({ categories: result.data, processing: false });
        })
        .catch(err){
            this.setState({ categories: null, processing: false });
        };
};

0
投票

SOLUTION:错误的依存关系使DOM无法重新呈现。基本上我什至没有安装React。转到另一个已经安装了React并像魅力一样工作的项目,清理了一些代码并了解了很多有关babel的知识。从我的错误中学习😅


-1
投票

我认为您的最后一部分应该更改,应该是ReactDOM.render(),而不是render()

if (element) {
  ReactDOM.render(
    <Employment />,
    element
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.