简体   繁体   中英

AntD Rate DefaultValue Doesn't Get the Value

The defaultValue function of AntD Rate doesn't work. Or I do something wrong.

Here is my main page:

const BookPage = () => {
    ...
    const [state, setState] = useState({});

    useEffect(() => {
        fetch()
    }, [])

    async function fetch() {
        ...
        const rate = await UserBookService.fetchRate(bookId);

        await setState({..., rate: rate});
    }

My return function:

    console.log(state.rate)
    return (
        <>
            <div style={{width: "fit-content", display: "inline-block", marginLeft: "200px"}}>
            ...

                <div style={{display: "inline-block", float: "right", marginLeft: "50px", marginTop: "70px"}}>
                    ...
                    <hr/>
                    <Rate defaultValue={state.rate} onChange={(value) => onChange(value)}></Rate>
                </div>
            </div>
        </>
    )

The result of console.log(state.rate) :

undefined
undefined
5
5

So, it's probably because of the undefined lines but I don't know how to solve it.

There are 2 problems:

1, You have duplicate values when printing. The fix is to remove or comment the

<React.StrictMode></React.StrictMode>

tag in the index.js file

2, useEffect only executes when the component has been rendered, undefined when the component is rendering, so it defaults to an empty object {}.rate = undefined

Please check its value before using

Here is the solution I found, I had to change the RateSection from function component to class component. So that, I could use an if-else statement on the render method.

import {Rate} from "antd";
import UserBookService from "../../service/user/UserBookService";
import React from "react";

class RateSection extends React.Component {
    state = {
        rate: undefined
    }

    constructor(props) {
        super(props);
        this.getCurrentRate().then(value => this.setState({rate: value}));
    }

    getCurrentRate = async () => {
        return await UserBookService.fetchRate(this.props.bookid);
    }

    onChange = async (value) => {
        await UserBookService.addRate(this.props.bookid, value);
    }

    render() {
        if (this.state.rate !== undefined) {
            return (
                <Rate defaultValue={this.state.rate} onChange={(value) => this.onChange(value)}></Rate>
            )
        }
    }
}

export default RateSection;

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