首页 > 解决方案 > 我的 React 函数作为道具被传递,没有被调用

问题描述

我正在尝试根据单击按钮重新呈现页面。我有在我的应用程序组件updateCowList中调用的函数。逻辑在我处理按钮和文本输入的组件中setState()handleClicknewCow

我看到的console.logs()是“火”,但我没有看到“之后” ,也没有看到Appconsole.log()中我的函数中的任何日志。updateCowList

我怎样才能让我的updateCowList功能运行?我尝试过以各种方式调用它,解构道具等。

这是我的应用程序:

    import React from 'react';
    import CowList from './CowList.jsx';
    import CowListEntry from './CowListEntry.jsx';
    import axios from 'axios';
    import SearchDB from './searchDB.js';
    import NewCow from './NewCow.jsx';
    
    
    class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          cows: []
        }
        // this.updateCowList = this.updateCowList.bind(this);
      }
    
      componentDidMount() {
        SearchDB()
        .then((res) => {
          this.setState({cows: res.data})
        }, (err) => {
          console.log(err);
        });
      }
    
      updateCowList(cow) {
        console.log('update cow list is running')
        oldCows = [...this.state.cows];
        newCows = oldCows.push(cow);
        console.log('new cows be4 set state', newCows);
        this.setState({cows: newCows});
        console.log('new cows after set state', newCows);
      }
    
      render() {
        return (
          <div>
          <CowList cows={this.state.cows}/>
          <NewCow props={this.updateCowList}/>
          </div>
        )
      }
    }
    
    export default App;

这是我的NewCow组件:

    import React from 'react';
    import axios from 'axios';
    
    class NewCow extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          entry: ''
        };
        this.handleChange = this.handleChange.bind(this);
        this.handleClick = this.handleClick.bind(this);
      }
    
       handleClick () {
        let split = this.state.entry.split(', ')
        console.log(split)
        axios.post('http://localhost:3000/api/cows', {
          name: split[0],
          description: split[1]
        })
          .then(res => { console.log('fire', res.data);
            this.props.updateCowList(res.data);
            console.log('after')
          })
          .catch(err => 'error submitting cow :( mooooo');
      }
    
      handleChange (event) {
        this.setState({entry: event.target.value})
      }
    
    
      render () {
        return (
        <div className='newCowForm'>
        <input className='form-control' type='text' onChange={this.handleChange} value={this.state.entry} placeholder={'name, description'} />
        <button onClick={this.handleClick} className='newCowButton'>Create new cow</button>
        </div>
        )
      }
    }
    
    export default NewCow;

标签: javascriptreactjs

解决方案


<NewCow props={this.updateCowList}/>

应该 :

<NewCow updateCowList={this.updateCowList}/>

推荐阅读