if else 语句在反应组件中不起作用

时间:2021-05-14 22:27:58

标签: reactjs

我正在尝试在我的 react 组件中实现一个条件。当用户触发 onClick 时,状态会更新 allStakes,创建一个包含 4 个值的数组。问题是我不希望用户输入超过 4 个值,所以试图通过执行 if else 语句来给出限制。我试图在两个语句中添加一个 console.log。奇怪的事实是 setState 得到更新,但 csonole.log 永远不会显示。即使数组长于 4,组件也会继续呈现我插入的所有值。谢谢提前

import React, { Component } from 'react';
import Stake from './stake';

class FetchRandomBet extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: true,
            bet: null,
            value: this.props.value,
            allStakes: []
        };
    }

    async componentDidMount() {
        const url = "http://localhost:4000/";
        const response = await fetch(url);
        const data = await response.json();

        this.setState({
            loading: false,
            bet: data.bets,
        });
    }

    render() {
        const { valueProp: value } = this.props;
        const { bet, loading } = this.state;
        const { allStakes } = this.state;

        if (loading) {
            return <div>loading..</div>;
        }
        if (!bet) {
            return <div>did not get data</div>;
        }
        return (
            < div >
                {
                    loading || !bet ? (
                        <div>loading..</div>
                    ) : value === 0 ? (
                        <div className="bet-list">
                            <ol>
                                <p>NAME</p>
                                {
                                    bet.map(post => (
                                        <li key={post.id}>
                                            {post.name}
                                        </li>
                                    ))
                                }
                            </ol>
                            <ul>
                                <p>ODDS</p>
                                {
                                    bet.map(post => (
                                        <li key={post.id}>
                                            {post.odds[4].oddsDecimal}
                                            <div className="stake-margin">
                                                <Stake
                                                    onClick={(newStake) => {
                                                        if (allStakes.length <= 3) {
                                                            this.setState({ allStakes: [allStakes, ...newStake] })
                                                            console.log('stop')
                                                        } else if (allStakes.length == 4) {
                                                            console.log('more than 3')
                                                        }
                                                    }}
                                                />
                                            </div>
                                        </li>
                                    ))
                                }
                            </ul>
                        </div>

3 个答案:

答案 0 :(得分:0)

可能是因为数组解构不正确。尝试更改此代码:

  this.setState({ allStakes: [allStakes, ...newStake] })

下一个:

 this.setState({ allStakes: [newStake, ...allStakes] })

答案 1 :(得分:0)

您的状态属于您的 FetchRandomBet 组件,并且您正尝试从您导入的组件更新它。有两种解决方案。

1> 将您的 Stake 组件包装到一个单独的组件中,并使用类似这样的 onClick 处理程序

<div onClick={(newStake) => {
    if (allStakes.length <= 3) {
        this.setState({
            allStakes: [allStakes, ...newStake
            ]
        })
        console.log('stop')
    } else if (allStakes.length == 4) {
        console.log('more than 3')
    }
}}><Stake /></div>

2> 将状态作为道具传递给 Stake 组件,该组件将负责更新 FetchRandomBet 的状态。像这样

<Stake parentState={this}/>

在 Stake 组件内,点击您想要的任何位置更改 parentState

答案 2 :(得分:0)

我解决了这个问题。我转移了权益组件中的 onClick 方法,并使用数组 useState 处理了公共数组的上传。我将值添加到 newStake,当我单击确定时,我检索 newStake 并将其分散到一个新数组中,然后检查该数组。如果有一个值不应该继续添加,否则它可以添加值。它工作正常。还是谢谢

import React, { useState } from 'react';
import CurrencyInput from 'react-currency-input-field';

function Stake(props) {
    const [newStake, setStake] = useState(null);
    const [allStakes, setStakes] = useState(null);

    const changeStake = (e) => {
        setStake([e.target.value])
    }

    const mySubmit = () => {
        if (!allStakes) {
            setStakes([...newStake, allStakes])
            props.onClick(newStake);
        } else if (allStakes) {
            console.log('stop')
        }
    }

    return (
        <>
            <CurrencyInput
                onChange={changeStake}
                style={{
                    marginLeft: "40px",
                    width: "50px"
                }}
                placeholder="Stake"
                decimalScale={2}
                prefix="£"
            />
            <button onClick={mySubmit}>yes</button>
            <button>no</button>
            {newStake}
        </>
    );
}

export default Stake;