在 React 方面,我完全是个菜鸟,这很可能是一个简单的问题,但它几乎让我抓狂。
代码如下:
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;
当呈现组件时,我得到 "Unhandled Rejection (TypeError): log.push is not a function"
。传递给组件的所有属性都是字符串。
最佳答案
除了@CD 的回答外,您不想在指定的 setState
方法之外直接操作 state
。在这种情况下,您可以使用 concat
返回一个新数组并将其分配给状态变量。像这样
this.setState({ priceLog: this.state.pricelog.concat(this.props.price)});
您对 console.log
的第二次调用可能不会提供预期的结果,因为 setState
是异步调用。如果你想访问新的状态变量,你必须使用这样的回调
this.setState({
priceLog: this.state.pricelog.concat(this.props.price)
}, () => console.log(this.state.pricelog));
关于javascript - React.js .push() 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45297601/