在异常情况下迷失方向

时间:2018-01-09 21:18:11

标签: javascript reactjs babeljs babel

我正在尝试将道具从我的父组件传递到我的子组件。当我收到componentWillReceiveProps()中的道具时,我的硬币道具的一个孩子迷路了。这可以通过子组件中的console.log行看到。

由于某种原因,coin.profit打印“undefined”,而只打印硬币对象显示coin.profit确实在硬币对象中。我已经查看了几个小时的代码,并要求朋友们查看它并且无济于事。任何帮助将不胜感激。

子组件(https://github.com/kdelalic/cryptofolio/blob/master/src/js/progress.js):

class Progress extends Component {

constructor(props) {
    super(props);

    this.state = {
        initial: 0,
        profit: 0,
        holdings: 0,
        change: "0%"
    };
}

componentWillReceiveProps(nextProps) {
    if (nextProps.coins !== this.props.coins) {
        Object.keys(nextProps.coins).map((key) => {
            const coin = nextProps.coins[key]
            console.log(coin)
            console.log(coin.price)
            console.log(coin.profit)
            this.setState({
                initial: this.state.initial + coin.price * coin.amount,
                profit: this.state.profit,
                holdings: this.state.profit + this.state.holdings,
                change: this.state.initial / this.state.profit * 100 + "%",
            })
        })
    }
}

父组件(https://github.com/kdelalic/cryptofolio/blob/master/src/js/crypto.js):

class Crypto extends Component {
constructor(props) {
    super(props);

    this.state = {
        open: false,
    };
}

getCurrentPrice = (key) => {
    const { coins } = this.state;
    var url = "https://min-api.cryptocompare.com/data/price?fsym=" + coins[key].value.substring(coins[key].value.indexOf("(")+1,coins[key].value.indexOf(")")).toUpperCase() + "&tsyms=" + coins[key].currency.toUpperCase();
    axios.get(url)
        .then(response => {
            const price = response.data[coins[key].currency.toUpperCase()];
            const profit = parseFloat((price - coins[key].price) * coins[key].amount).toFixed(2)

            var newState = this.state;
            newState.coins[key]["currentPrice"] = price;
            newState.coins[key]["profit"] = profit;
            this.setState(newState);
        })
        .catch(err => {               
            console.log(err)
        });     
};

checkPos = (num) => {
    if (num > 0) {
        return " positive"
    } else if (num < 0) {
        return " negative"
    } else {
        return ""
    }
};

handleOpen = () => {
  this.setState({ ...this.state, open: true });
};

handleClose = () => {
  this.setState({ ...this.state, open: false });
};

coinData = (dataFromChild, key) => {
    const newCoins = {
        ...this.state.coins
    };
    newCoins[key] = dataFromChild
    this.setState({
        ...this.state,
        coins: newCoins
    }, () => {
        this.getCurrentPrice(key);
        this.setState({
            ...this.state,
        })
        this.handleClose();
    })
};

render() {
    const { coins } = this.state;
    return (
        <div className="crypto">
            <Progress coins={this.state.coins}/>

1 个答案:

答案 0 :(得分:1)

在React中,你永远不应该改变现有的状态。在

var newState = this.state;
newState.coins[key]["currentPrice"] = price;
newState.coins[key]["profit"] = profit;
this.setState(newState);

您永远不会创建任何新对象。你应该做的

this.setState({
  ...this.state,
  coins: {
    ...this.state.coins,
    [key]: {
      ...this.state.coins[key],
      currentPrice: price,
      profit,
    },
  },
});

为您要变异的每个项目创建新的状态对象。

因为您正在修改现有对象,意味着传递给componentWillReceiveProps的对象可能会被其他代码更新。