Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.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 React-未将Ajax数据传递到子组件_Javascript_Reactjs - Fatal编程技术网

Javascript React-未将Ajax数据传递到子组件

Javascript React-未将Ajax数据传递到子组件,javascript,reactjs,Javascript,Reactjs,我有两个部分,一个是父母,一个是孩子。我在componentDidMount()回调中使用fetch方法。一旦我这样做了,我就用关键项将状态设置为从api中提取的数据。一旦我这样做了,它应该能够作为一个道具登录到子组件中。然而,这是行不通的。我做错了什么 父组件: import React, {Component} from 'react'; import Map from './maps/Map'; class Main extends Component { constructor

我有两个部分,一个是父母,一个是孩子。我在
componentDidMount()
回调中使用fetch方法。一旦我这样做了,我就用关键项将状态设置为从api中提取的数据。一旦我这样做了,它应该能够作为一个道具登录到子组件中。然而,这是行不通的。我做错了什么

父组件:

import React, {Component} from 'react';
import Map from './maps/Map';

class Main extends Component {
    constructor(props){
        super(props);
        this.state = {
            name: "John",
            items: []
        }
    }

    componentDidMount() {
        fetch('https://hn.algolia.com/api/v1/search?query=')
        .then(dat => dat.json())
        .then(dat => {
            this.setState({
                items: dat.hits
            })
        })
    }

    render() {
        return (
            <div>
                <Map list={this.state.name} items={this.state.items}></Map>
            </div>
        )
    }
}

export default Main;
import React, {Component} from 'react';

class Map extends Component {

    constructor(props) {
        super(props);
        console.log(props.items)
    }

    render () {
        return (
            <h1>{this.props.name}</h1>
        )
    }
}

export default Map;
import React,{Component}来自'React';
从“./maps/Map”导入地图;
类主扩展组件{
建造师(道具){
超级(道具);
此.state={
姓名:“约翰”,
项目:[]
}
}
componentDidMount(){
取('https://hn.algolia.com/api/v1/search?query=')
.then(dat=>dat.json())
。然后(dat=>{
这是我的国家({
项目:dat.hits
})
})
}
render(){
返回(
)
}
}
导出默认主;
子组件:

import React, {Component} from 'react';
import Map from './maps/Map';

class Main extends Component {
    constructor(props){
        super(props);
        this.state = {
            name: "John",
            items: []
        }
    }

    componentDidMount() {
        fetch('https://hn.algolia.com/api/v1/search?query=')
        .then(dat => dat.json())
        .then(dat => {
            this.setState({
                items: dat.hits
            })
        })
    }

    render() {
        return (
            <div>
                <Map list={this.state.name} items={this.state.items}></Map>
            </div>
        )
    }
}

export default Main;
import React, {Component} from 'react';

class Map extends Component {

    constructor(props) {
        super(props);
        console.log(props.items)
    }

    render () {
        return (
            <h1>{this.props.name}</h1>
        )
    }
}

export default Map;
import React,{Component}来自'React';
类映射扩展组件{
建造师(道具){
超级(道具);
控制台日志(道具项)
}
渲染(){
返回(
{this.props.name}
)
}
}
导出默认地图;

首先,
fetch
是异步的。因此,当您尝试在子构造函数中console.log结果时,fetch语句可能处于挂起状态


将console.log放在
呈现
方法中会起作用,因为如果状态
更改,组件将重新呈现。

首先,
获取
是异步的。因此,当您尝试在子构造函数中console.log结果时,fetch语句可能处于挂起状态

将console.log放在
呈现
方法中会起作用,因为如果状态
更改,组件将重新呈现。

组件的在生命周期中只运行一次。当它这样做时,
props.items
是未定义的,因为您的ajax请求正在进行中,所以
console.log(props.items)
不会显示任何内容

如果将构造函数更改为
console.log(“constructed”),您将看到一次性输出(堆栈代码段可能不会显示此内容——请在浏览器控制台中查看)。从今以后,可以使用它查看ajax请求完成时设置的新道具

您还可以将道具记录在
render
方法中,该方法将在ajax请求解析之前运行一次,然后在
props.items
更改时再次运行

作为一个补充点,您有

  • {JSON.stringify(e,null,2)}
  • )} ); } } 类Main扩展了React.Component{ 建造师(道具){ 超级(道具); this.state={name:“John”,项:[]}; } componentDidMount(){ 取('https://hn.algolia.com/api/v1/search?query=') .then(dat=>dat.json()) 。然后(dat=>{ this.setState({items:dat.hits}) }); } render(){ 报税表( ); } } render(,document.body)
    
    
    组件的在生命周期中仅运行一次。当它这样做时,
    props.items
    是未定义的,因为您的ajax请求正在进行中,所以
    console.log(props.items)
    不会显示任何内容

    如果将构造函数更改为
    console.log(“constructed”),您将看到一次性输出(堆栈代码段可能不会显示此内容——请在浏览器控制台中查看)。从今以后,可以使用它查看ajax请求完成时设置的新道具

    您还可以将道具记录在
    render
    方法中,该方法将在ajax请求解析之前运行一次,然后在
    props.items
    更改时再次运行

    作为一个补充点,您有
    
    
  • {JSON.stringify(e,null,2)}
  • )} ); } } 类Main扩展了React.Component{ 建造师(道具){ 超级(道具); this.state={name:“John”,项:[]}; } componentDidMount(){ 取('https://hn.algolia.com/api/v1/search?query=') .then(dat=>dat.json()) 。然后(dat=>{ this.setState({items:dat.hits}) }); } render(){ 报税表( ); } } render(,document.body)
    您唯一的问题是,您试图使用
    this.props.name
    映射
    组件道具被称为
    列表
    项目
    ,因此它将返回
    未定义

    如果您将道具记录在构造函数中,您将获得
    Main
    的初始状态,因为提取尚未返回任何内容。请记住,构造函数只运行一次。因此,当您在构造函数中记录
    props.items
    时,可能会得到一个空数组,因为这是您在初始状态下所拥有的

    import CircularProgress from "@material-ui/core/CircularProgress"
    
    class Main extends Component {
      constructor(props) {
        super(props);
        this.state = {
          name: "John",
          items: [],
          fecthed: false
        };
      }
    
      componentDidMount() {
        fetch("https://hn.algolia.com/api/v1/search?query=")
          .then(dat => dat.json())
          .then(dat => {
            this.setState({
              items: dat.hits,
              fecthed: true
            });
          });
      }
    
      render() {
        return (
          <Map
            fetched={this.state.fecthed}
            list={this.state.name}
            items={this.state.items}
          />
        );
      }
    }
    
    class Map extends Component {
      render() {
        return (
          <div>
            {this.props.fetched ? (
              <div>
                <h1>{this.props.list}</h1>
                {this.props.items.map((item, indx) => (
                  <div key={indx}>Author: {item.author}</div>
                ))}
              </div>
            ) : (
              <CircularProgress />
            )}
          </div>
        );
      }
    }
    
    如果在渲染方法中记录道具,您将看到数组中填充了您获取的数据,如您在此处所见:

    如果在获取数据之前不想显示组件,可以在状态中包含一个布尔属性,在获取返回响应并将其作为道具传递给组件后,将该属性设置为true。组件可以使用该变量来显示,例如,在获取数据时显示微调器。下面是一个例子:

    从“@material ui/core/CircularProgress”导入循环进度
    类主扩展组件{
    建造师(道具){
    超级(道具);
    此.state={
    姓名:“约翰”,
    项目:[],
    错误的
    };
    }
    componentDidMount(){
    取回(“https://hn.algolia.com/api/v1/search?query=")
    .then(dat=>dat.json())
    。然后(dat=>{
    这是我的国家({
    项目:dat.hits,
    粪便:t