简体   繁体   中英

React.js .push() is not a function

I'm a total rookie when it comes to React and this is most likely a simple issue, but it nearly drove me nuts.

The code is following:

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;

I get "Unhandled Rejection (TypeError): log.push is not a function" when the component is rendered. All properties passed to the component are strings.

Besides the answer from @CD, you do not want to directly manipulate a state outside the designated setState method. In this case you could use concat to return a new array and assign that to the state variable. Something like this

this.setState({ priceLog: this.state.pricelog.concat(this.props.price)});

And your second call to the console.log might not deliver the desired results since setState is an asynchronous call. If you want to access the new state variable you have to use a callback like this

 this.setState({
     priceLog: this.state.pricelog.concat(this.props.price)
 }, () => console.log(this.state.pricelog));

push returns the new length of the array so replace:

log = log.push(this.props.price);

with:

log.push(this.props.price);   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM