简体   繁体   中英

React - JSX is not changing on conditional rendering

I am doing a conditional rendering in my code in which i need to change the component called according to the state when it changes every time. Default option is Unpaid. When I select Paid 1st time state changes to the paid and component also changes to paid but after that if I changes to Unpaid state is changing but the Component is stuck to Paid. What can be the issue? Code is attached.

import React, { useState } from "react";

import Paid from "./Paid";
import Unpaid from "./Unpaid";

const Payment = () => {
    const [paid, setPaid] = useState(0);

    return (
        <React.Fragment>
            <div className="container">
                <br />
                <div className="row">
                    <div className="col-sm-4">
                        <select
                            className="browser-default custom-select"
                            onChange={(option) => setPaid(option.target.value)}
                            required
                        >
                            <option value="0">Unpaid</option>

                            <option value="1">Paid</option>
                        </select>
                    </div>
                    <div className="col-sm-8"></div>
                </div>
                <br />
                <div>{paid ? <Paid /> : <Unpaid />}</div>
            </div>
        </React.Fragment>
    );
};

export default Payment;

您需要解析option.target.value ,因为它总是评估为true因为输入总是输出一个字符串,它总是真。

onChange={(option) => setPaid(JSON.parse(option.target.value))}

add + to convert the string value to a number 0 or 1

 onChange={(option) =>{let val=+option.target.value ;setPaid(val);}}

 let a="0" let b="1" console.log(+a,+b) let c=+a c? console.log("test 1"):console.log("test 2")

以这种方式更新您的状态

({ target: { value } }) => setPaid(value)

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