我正在将一个函数传递给子组件来修改FilterableProductTable的状态,当我在这里做控制台日志时工作正常,即使它给了我这个错误 ' Uncaught TypeError:this.setState不是函数 在Object.handleInsertItems [as insertItems]'
handleInsertItems(newItem){
console.log(newItem);
this.setState(prevState => ({
active: prevState.active,
items: prevState.items.concat('am')
}));
无论如何它没有更新项目的状态,或者我看不到更改,
class ProductRow extends React.Component {
constructor(props){
super(props);
this.state= {active: false};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
active: !prevState.active
}));
this.props.insertItems(this.props.name);
}
render() {
return (
<p className={ this.state.active ? 'active service' : 'service' } onClick={this.handleClick}>
{this.props.name}
</p>
);
}
}
class ProductTable extends React.Component {
render() {
var rows = [];
var lastCategory = null;
var func = this.props.insertItems;
this.props.products.forEach(function(product) {
if (product.category !== lastCategory) {
rows.push(<ProductCategoryRow category={product.category} key={product.category} />);
}
rows.push(<ProductRow name={product.name} insertItems={func} />);
lastCategory = product.category;
});
return (
<div id="services">
{rows}
</div>
);
}
}
class FilterableProductTable extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: [],
};
}
fetch() {
axios.get(this.props.getSite)
.then(res => {
this.setState({
posts: res.data.functionality
});
});
}
componentDidUpdate(){
this.fetch();
}
componentDidMount() {
this.fetch();
}
render() {
return (
<div>
<ProductTable products={this.state.posts} insertItems={this.props.insertItems}/>
</div>
);
}
}
export class App extends React.Component {
constructor(props){
super(props);
this.state= {active: true, items: ['noe']};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
active: !prevState.active
}));
}
handleInsertItems(newItem){
console.log(newItem);
this.setState(prevState => ({
active: prevState.active,
items: prevState.items.concat('am')
}));
}
render() {
console.log('newITem');
return (
<div>
<FilterableProductTable
getSite={ this.state.active ? '/get_platforms' : '/get_features' }
insertItems={this.handleInsertItems}
/>
<a className={ this.state.active ? 'button' : 'hidden' } onClick={this.handleClick}><span>Next</span></a>
<TotalComponent items={this.state.items}/>
</div>
);
}
}
答案 0 :(得分:1)
创建作为params传递的任何函数的绑定版本,因为子组件不会使用正确的上下文调用该函数。在你的构造函数中:
this.handleInsertItems = this.handleInsertItems.bind(this);