Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/373.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 第一次单击时未更新的反应状态和未渲染的组件_Javascript_Reactjs_Setstate - Fatal编程技术网

Javascript 第一次单击时未更新的反应状态和未渲染的组件

Javascript 第一次单击时未更新的反应状态和未渲染的组件,javascript,reactjs,setstate,Javascript,Reactjs,Setstate,retrieveInTransit()是单击处理程序。API调用检索数据并将对象数组返回到setState()函数中的新状态对象中。第一次单击记录泵属性的空数组。如果我再次单击它,我将获得填充的泵阵列。为什么我必须点击两次?即使render()函数中的日志返回作为设备组件的道具传入的正确泵阵列,设备组件也不会呈现。我对此不知所措,任何帮助都将不胜感激 import React, { Component } from 'react'; import {ListGroup} from 'reacts

retrieveInTransit()
是单击处理程序。API调用检索数据并将对象数组返回到
setState()
函数中的新状态对象中。第一次单击记录
属性的空数组。如果我再次单击它,我将获得填充的
泵阵列。为什么我必须点击两次?即使
render()
函数中的日志返回作为
设备组件的道具传入的正确泵阵列,设备组件也不会呈现。我对此不知所措,任何帮助都将不胜感激

import React, { Component } from 'react';
import {ListGroup} from 'reactstrap';
import Equipment from './Equipment';

class Transit extends Component {
  constructor(props) {
    super(props);
    this.state = {
      pending: false,
      pumps: []
    };
  }

  handleCancelClick = (index) => {
    this.setState((prevState) =>
      prevState.pumps[index].isCancelled = !prevState.pumps[index].isCancelled
    );

    this.setState((prevState) => {
        prevState.pumps.every((equipment) => equipment.isCancelled === false)
          ? prevState.pending = false: prevState.pending = true
      }
    )};


  populate_transit = () => {
    let pumpArray = [];
    fetch('http://192.168.86.26:8000/api/v1/transit_list', {mode: 'cors'})
      .then(response => response.json())
      .then(MyJson => MyJson.map((entry) =>{
        if (document.getElementsByClassName('title')[0].innerText.toLowerCase().includes(entry.transferfrom)) {
          pumpArray.push(
            {
              unitnumber: entry.unitnumber,
              id: entry.id,
              message: entry.unitnumber + ' was moved to ' + entry.transferto,
              isCancelled: false
            });
        }}));

    return pumpArray
  };


  cancelTransit = () => {
    let cancelled = this.state.pumps.filter((movement) => movement.isCancelled);
    let cancelledId = cancelled.map((object) => object.id);
    fetch('http://192.168.86.26:8000/api/v1/transit_list/', {
      method:'POST',
      mode: 'cors',
      body: JSON.stringify(cancelledId),
      headers:{
        'Content-Type': 'application/json'
      }
        }
      );
    this.populate_transit()
  };

  retrieveInTransit = () => {
    if (this.state.pending) {
      this.setState({
        pending: false,
        pumps: this.cancelTransit()
      }, console.log(this.state))} else {
      this.setState({
        pending: false,
        pumps: this.populate_transit()
      }, console.log(this.state))
    }

  };


  render() {
    console.log(this.state.pumps);
    return (
      <ListGroup>
        <Equipment transitequipment={this.state.pumps} cancelClick={this.handleCancelClick}/>
        <button className='btn btn-dark' onClick={this.retrieveInTransit}>
          {this.state.pending ? 'Submit Cancellations': 'Refresh'}
        </button>
      </ListGroup>
    );
  }
}

export default  Transit;
import React,{Component}来自'React';
从“reactstrap”导入{ListGroup};
从“./设备”导入设备;
类传输扩展组件{
建造师(道具){
超级(道具);
此.state={
待定:错误,
泵:[]
};
}
handleCancelClick=(索引)=>{
this.setState((prevState)=>
prevState.pumps[index].isCancelled=!prevState.pumps[index].isCancelled
);
this.setState((prevState)=>{
prevState.pumps.every((设备)=>equipment.isCancelled===false)
?prevState.pending=false:prevState.pending=true
}
)};
填充_transit=()=>{
让pumpArray=[];
取('http://192.168.86.26:8000/api/v1/transit_list“,{mode:'cors'})
.then(response=>response.json())
.then(MyJson=>MyJson.map((条目)=>{
if(document.getElementsByClassName('title')[0].innerText.toLowerCase().includes(entry.transferfrom)){
推(
{
unitnumber:entry.unitnumber,
id:entry.id,
消息:entry.unitnumber+已移动到“+entry.transferto”,
已取消:错误
});
}}));
回程泵道
};
取消传输=()=>{
让取消=此.state.pumps.filter((移动)=>movement.isCancelled);
让canceledid=cancelled.map((object)=>object.id);
取('http://192.168.86.26:8000/api/v1/transit_list/', {
方法:'POST',
模式:“cors”,
正文:JSON.stringify(canceledid),
标题:{
“内容类型”:“应用程序/json”
}
}
);
这个。填充_transit()
};
retrieveInTransit=()=>{
if(this.state.pending){
这是我的国家({
待定:错误,
泵:这个。取消传输()
},console.log(this.state))}else{
这是我的国家({
待定:错误,
泵:这个。填充_transit()
},console.log(this.state))
}
};
render(){
console.log(此.state.pumps);
返回(
{this.state.pending?'Submit Cancellations':'Refresh'}
);
}
}
出口默认过境;
因此,在上面的代码中,您将在
fetch
调用之外返回
pumpArray
。由于
fetch
调用
api
resolve
承诺需要时间,因此您的
pumpArray
=
[]
的当前值就是为什么首先得到空数组的原因。在
下一步中,单击
promise
解决
,因此您可以获得
泵阵列

要解决此问题,请将
泵阵列
移动到
内部,然后

设置状态的第二个参数需要一个函数,将console.log(this.state)的结果传递给它(立即执行日志,而不是“在”状态更改之后)@K。。但是每次调用
setState
时,都会发生重新渲染,在这种情况下,渲染方法中的
console.log
应该记录更新的状态,对吗?您必须使用()=>console.log(this.state),否则它将在调用setStateMan之前执行!锐利的眼睛:指的是。这是有道理的。我进行了重组,以便现在从.then()中返回pumpArray。现在我正在处理state.pumps在设置状态后未定义的问题。能否从withing.then()返回值?可能与调用传递给setState的对象内的函数有关?见鬼。谢谢大家。我试图用一些还不存在的东西来设置状态。
 populate_transit = () => {
let pumpArray = [];
fetch('http://192.168.86.26:8000/api/v1/transit_list', {mode: 'cors'})
  .then(response => response.json())
  .then(MyJson => MyJson.map((entry) =>{
    if (document.getElementsByClassName('title')[0].innerText.toLowerCase().includes(entry.transferfrom)) {
      pumpArray.push(
        {
          unitnumber: entry.unitnumber,
          id: entry.id,
          message: entry.unitnumber + ' was moved to ' + entry.transferto,
          isCancelled: false
        });
    }}));

return pumpArray};