相关疑难解决方法(0)

如何取消componentWillUnmount上的提取

我认为标题说明了一切.每次卸载仍在提取的组件时都会显示黄色警告.

警告:无法在卸载的组件上调用setState(或forceUpdate).这是一个无操作,但是......要修复,取消componentWillUnmount方法中的所有订阅和异步任务.

  constructor(props){
    super(props);
    this.state = {
      isLoading: true,
      dataSource: [{
        name: 'loading...',
        id: 'loading',
      }]
    }
  }

  componentDidMount(){
    return fetch('LINK HERE')
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({
          isLoading: false,
          dataSource: responseJson,
        }, function(){
        });
      })
      .catch((error) =>{
        console.error(error);
      });
  }
Run Code Online (Sandbox Code Playgroud)

reactjs

73
推荐指数
4
解决办法
4万
查看次数

无法在卸载的组件上调用setState(或forceUpdate)

我试图在组件更新后从服务器获取数据,但我无法做到这一点.据我所知componentWillUnmount,当组件即将被销毁时被调用,但我永远不需要销毁它因此对我来说没用.这会是什么解决方案?什么时候我应该设置状态?

async componentDidUpdate(prevProps, prevState) {
  if (this.props.subject.length && prevProps.subject !== this.props.subject) {
    let result = await this.getGrades({
      student: this.props.id,
      subject: this.props.subject
    });
    this.setState({
      subject: this.props.subject,
      grades: result
    });
  }
}

async getGrades(params) {
  let response, body;

  if (params['subject'].length) {
    response = await fetch(apiRequestString.gradesBySubject(params));
    body = await response.json();
  } else {
    response = await fetch(apiRequestString.grades(params));
    body = await response.json();
  }

  if (response.status !== 200) throw Error(body.message);

  return body;
}
Run Code Online (Sandbox Code Playgroud)

完整错误:

Warning: Can't call setState (or forceUpdate) on an unmounted …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-lifecycle

22
推荐指数
1
解决办法
2万
查看次数

在生命周期方法React JS中设置状态

我有React生命周期方法如下:

componentWillReceiveProps(nextProps){
    if(this.props.totalVehicles !== nextProps.totalVehicles){
        this.setState({animation: "cartCount"}, () => setTimeout(() =>  this.setState({animation: null}), 1000));
    }
}
Run Code Online (Sandbox Code Playgroud)

但这给了我:

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the Header component.
Run Code Online (Sandbox Code Playgroud)

如何在生命周期方法中设置状态而不会出现这些错误?

reactjs

5
推荐指数
1
解决办法
3529
查看次数

5
推荐指数
1
解决办法
194
查看次数

使用react调用api的正确方法

我有一个如下的反应代码,它基本上创建了一个树形图:

class ChartModal extends Component{
   constructor(props){
      super(props)
}
callApi(){

  fetch(someurl)
  .then((result) => {

    return result.json();
  }).then((jsonResult) => {
    console.log(jsonResult);
  })
}
render(){
  return(
    <Modal
            onOk={() => this.props.toggleVisibility()}
            onCancel={() => this.props.toggleVisibility()}
            visible={this.props.isVisible}
            okText={'ok'}
            cancelText={'cancel'}
            confirmLoading={false}
            title="Intent distribution chart"
        >
            <h1>HOWDY</h1>
            <TreeMap
                data =  {this.callApi()}//this is where i want the data returned by apicall
                width={400}
                valueUnit={'count'}
            />
        </Modal>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

现在我希望 api 调用返回的数据在组件内部使用tree map,但我现在的方式似乎不起作用。当我运行这个时,尽管我希望返回的数据存在,但tree map结果为空。jsonapi call

javascript d3.js reactjs react-native

4
推荐指数
1
解决办法
1392
查看次数

React + Firebase取消订阅不是useEffect中的函数

我想了解为什么以下代码会触发此错误?

TypeError 取消订阅不是一个函数

.onSnapshot()当我使用函数而不是时,它没有这样的错误get()

谢谢

  useEffect(() => {
    const unsubscribe = database
      .collection("Maps")
      .doc(id)
      .collection("Entries")
      .get()
      .then(
        data => {
          data.forEach(doc => {
            console.log(doc.id, " => ", doc.data());
          });
          setLoading(false);
        },
        err => {
          setError(err);
          console.log(err);
        }
      );
    return () => unsubscribe();
  }, [id]);
Run Code Online (Sandbox Code Playgroud)

javascript firebase reactjs google-cloud-firestore

0
推荐指数
1
解决办法
1486
查看次数