如何在路由中放置功能

时间:2019-03-06 11:20:56

标签: reactjs react-native

作为一个初学者,我试图将“客户”列表放入要显示在路由/组件中的函数中,这可能吗?

App.js

  render() {

    return (
      <div className = "App">
      <div>
          <AddCliente onAdd = {this.onAdd} />
            </div>   
           <Router>
      <div>
              <Link to = "/">Cli</Link>

        <Route path = "/" exact component = {Adde} />
      </div>
    </Router>
      </div>
    );
  }
}

我想这样做:

function Adde() {
  return   <div>
  {
    this.state.clientes.map(cliente => {
      return (
       <ClienteItem
       key = {cliente.nome}
       {...cliente}
       onDelete = {this.onDelete}
       />
      );
    })
  }
   </div>;
}


export default Add;

错误:

TypeError: Cannot read property 'state' of undefined

1 个答案:

答案 0 :(得分:0)

You can do something like this in your component.

import React, { Component } from 'react';

class componentName extends Component {
   constructor(props) {
        super(props);
        this.state = {
         clients:[
         {
         name:'sdfd',
         title:'sdfd'
         }
         ]
        };
    }
    Adde=()=>{
      return(
          <div>
          {
            this.state.clientes.map(cliente => {
               return (
                 <ClienteItem
                      key = {cliente.nome}
                      {...cliente}
                      onDelete = {this.onDelete}
                   />
                );
            })
          }
          </div>
      );
    }
    render() {
        return (
          <div className = "App">
           <div>
             <AddCliente onAdd = {this.onAdd} />
           </div>   
          <Router>
            <div>
             <Link to = "/">Cli</Link>
             <Route path = "/" exact component = {Adde} />
            </div>
          </Router>
         </div>
       );
    }
}


export default componentName;