javascript - 我的 React 函数作为道具被传递,没有被调用
问题描述
我正在尝试根据单击按钮重新呈现页面。我有在我的应用程序组件updateCowList
中调用的函数。逻辑在我处理按钮和文本输入的组件中setState()
。handleClick
newCow
我看到的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;
解决方案
<NewCow props={this.updateCowList}/>
应该 :
<NewCow updateCowList={this.updateCowList}/>
推荐阅读
- sql - SQL Server如何查询每个设施每个产品的最大活动租金?
- css - 如果锚点内的“span”,如何在 CSS 中的第二个 div 元素内找到“span”元素?
- r - 使用 'rtweet' 通过 get_retweets 提取转推
- android - 无法在颤振中合并dex
- android - 不要导航到 WebView 中的其他页面,禁用链接和引用并返回第一页
- java - Android:约束布局中的多个片段
- flutter - Flutter PersistentFooterButtons 使用活动键盘不可见
- python - Scipy 拟合不能很好地收敛,也不能给出合理的误差估计
- swift - UserDefaults 未正确保存和递增
- docker - 将 docker 容器中的 SCTP 端口暴露给主机