简体   繁体   English

其他组件中的道具未定义 React

[英]Props in other component is undefined React

I'm newbie in React and trying to build a sample search filter with data from API.我是 React 的新手,正在尝试使用来自 API 的数据构建示例搜索过滤器。 Unfortunately I have problem with this code.不幸的是,我对这段代码有疑问。

It's get me an error,,Cannot read property 'filter' of undefined".它给我一个错误,无法读取未定义的属性“过滤器”。

It seems to me like child component doesn't get props from parent but I declared and imported this in code.在我看来,子组件没有从父组件获取道具,但我在代码中声明并导入了它。 I've tried everything what I found on the internet but nothing helps.我已经尝试了我在互联网上找到的所有内容,但没有任何帮助。 Can someone help me out with understanding what I made wrong?有人可以帮助我理解我做错了什么吗?

Child孩子

     import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Data from './Data';

class App extends Component {
  constructor() {
    super();
    this.state = {
      search : " "
    };
  }


updatedSearch(event) {
  this.setState(
    {search : event.target.value.substr(0,15)}
    )
}

  render () {

    console.log(this.props.names)
    let filterednames = this.props.names.filter(
      (name) => {
        return name.toLowerCase().indexOf(this.state.
          search.toLowerCase()) !== -1;
      }
    );
    return (  
        <div className = "App">
        <h1> Users list </h1>
        <Data />
        <input  type = "text" 
          placeholder = "Search by user name" 
          value = {this.state.search}
          onChange = {this.updatedSearch.bind(this)}
        />
        <ol>
            {filterednames.map(name => (
            <li key={name}>{name}</li>
            ))}
        </ol>
        </div>
    )
    
    }



}

ReactDOM.render(<App/>,document.getElementById('root'));



export default App;

Parent家长

import React, { Component } from 'react';
import App from './index';



class Data extends Component {
    constructor(props) {
      super(props);
      this.state = {
        names : [],
      }
    }

  
    componentDidMount() {
        fetch('https://jsonplaceholder.typicode.com/users')
          //Response
        .then(response => response.json())
        .then(output => {
           let data = output;
      
        //names in array
        let listaimion = [];

        for (let index = 0; index < data.length; index++) {
          listaimion.push(data[index].name)
         }
      
      this.setState({names : listaimion})
      })
    }

     
     render () {  
       return (
         <div className = "Data">
            <App  names = {this.state.names} /> 
         </div>
       )
     }
}
    
export default Data;

In the parent component, App needs to be declared.在父组件中,需要声明 App。 Also, App looks like your entry point of your application.此外,App 看起来像是您的应用程序的入口点。 Seems like, you might have mixed up Child and Parent here.看起来,您可能在这里混淆了 Child 和 Parent 。

Parent -家长 -

   import React, { Component } from 'react';
   import ReactDOM from 'react-dom';
   import Data from './Data';
    
   class App extends Component() {
   constructor() {
      this.state = {
        names : [],
      }
   }

  
    componentDidMount() {
        fetch('https://jsonplaceholder.typicode.com/users')
          //Response
        .then(response => response.json())
        .then(output => {
        let data = output;
        let listaimion = [];
        for (let index = 0; index < data.length; index++) {
          listaimion.push(data[index].name)
        }      
        this.setState({names : listaimion});
      });
    }

     
     render () {
       return (
         <div className = "Data">
          <Data  names = {this.state.names} /> 
         </div>       
       )
     }
    }

ReactDOM.render(<App/>,document.getElementById('root'));
export default App;

Child孩子

import React, { Component } from 'react';

class Data extends Component {
    constructor(props) {
      super(props);
    }

    render() {
      let filterednames = this.props.names.filter((name) => {
         return name.toLowerCase().indexOf(this.state.
           search.toLowerCase()) !== -1;
         }
      );
      return (<div>{filterednames.join(',')}</div>)
   }
}

The <App> component should be the parent - that is where your state should live. <App>组件应该是父组件 - 这是您的 state 应该存在的地方。 You would then pass this.state.names from <App> to <Data> inside the App render method.然后,您将在App渲染方法this.state.names<App>传递到<Data> You should not import App inside Data - App should render Data .您不应该在Data中导入App - App应该呈现Data

// App.js
class App extends Component {
  state = {
    names: []
  }
  componentDidMount(){
    // fetch data and when it's done use this.setState({ names: data })
  }
  render() {
    return <Data names={this.state.names}/>
  }
}
// Data.js
const Data = (props) => {
  return props.names.map(() => {...your map function})
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM