Javascript React.js.push()不是函数
我完全是一个新手,当谈到反应,这很可能是一个简单的问题,但它几乎让我发疯 代码如下:Javascript React.js.push()不是函数,javascript,reactjs,Javascript,Reactjs,我完全是一个新手,当谈到反应,这很可能是一个简单的问题,但它几乎让我发疯 代码如下: import React, { Component } from 'react'; class Tile extends Component { constructor(props) { super(props); this.state = { priceLog: [], diff: 'equal' };
import React, { Component } from 'react';
class Tile extends Component {
constructor(props) {
super(props);
this.state = {
priceLog: [],
diff: 'equal'
};
}
componentWillReceiveProps() {
let log = this.state.priceLog;
log = log.push(this.props.price);
this.setState({ priceLog: log });
console.log(this.state.priceLog);
}
render() {
return (
<div className="Tile">
Company: {this.props.name}<br/>
Price: {this.props.price}
<div className={this.state.diff}></div>
<button id={this.props.id}>Details</button>
</div>
);
}
}
export default Tile;
import React,{Component}来自'React';
类扩展组件{
建造师(道具){
超级(道具);
此.state={
价格日志:[],
差异:“平等”
};
}
组件将接收道具(){
让log=this.state.priceLog;
log=log.push(this.props.price);
this.setState({priceLog:log});
console.log(this.state.priceLog);
}
render(){
返回(
公司:{this.props.name}
价格:{this.props.Price}
细节
);
}
}
导出默认瓷砖;
我得到“未处理的拒绝(TypeError):当呈现组件时,log.push不是一个函数”
。传递给组件的所有属性都是字符串 返回数组的新长度,以便替换:
log = log.push(this.props.price);
与:
除了@CD的答案外,您不希望在指定的
setState
方法之外直接操作状态。在这种情况下,您可以使用concat
返回一个新数组并将其分配给状态变量。像这样的
this.setState({ priceLog: this.state.pricelog.concat(this.props.price)});
this.setState({
priceLog: this.state.pricelog.concat(this.props.price)
}, () => console.log(this.state.pricelog));
您对控制台.log的第二次调用可能无法提供所需的结果,因为setState
是一个异步调用。如果要访问新的状态变量,必须使用如下回调
this.setState({ priceLog: this.state.pricelog.concat(this.props.price)});
this.setState({
priceLog: this.state.pricelog.concat(this.props.price)
}, () => console.log(this.state.pricelog));
@DavidGevorgyan你是说语法()=>
?这是es5对function()…
调用的简写。如果你想使用它,你需要在你的项目中启用es5。谢谢!改为使用此样式:this.setState({priceLog:[…this.state.priceLog,this.props.price]},()=>console.log(this.state.priceLog));