簡體   English   中英

react掛鈎中的useState轉換為功能組件

[英]useState in react hooks converting to functional component

類組件代碼

import React, { Fragment, useState, Component } from 'react';
import styles from './styles';
import { withStyles } from '@material-ui/core/styles';
import classnames from 'classnames';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import IconButton from '@material-ui/core/IconButton';
import Button from '@material-ui/core/Button';
import ExpansionPanel from '@material-ui/core/ExpansionPanel';
import ExpansionPanelSummary from '@material-ui/core/ExpansionPanelSummary';
import ExpansionPanelDetails from '@material-ui/core/ExpansionPanelDetails';
import Typography from '@material-ui/core/Typography';

import Drawer from '@material-ui/core/Drawer';
import AppBar from '@material-ui/core/AppBar';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';

import Radio from '@material-ui/core/Radio';
import RadioGroup from '@material-ui/core/RadioGroup';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import FormControl from '@material-ui/core/FormControl';
import FormLabel from '@material-ui/core/FormLabel';

import Checkbox from '@material-ui/core/Checkbox';
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import dataStyles from '../../../../styles.css';

function TabContainer(props) {
    return (
        <Typography component="div" style={{ padding: 8 * 3 }}>
            {props.children}
        </Typography>
    );
}

const radioValues = [
    {
        label: 'Select All Providers for This Category',
        value: 'PRO',
    },
];

class SportsExpansion extends Component {
    state = {
        value: 0,
        spHeight: [],

        spLength: '',
    };

    componentDidMount() {
        this.setState({ spHeight: this.props.spHeight });

        if (
            this.props.spHeight.filter(
                check => check.spWeight === 'One'
            ).length > 0
        ) {
            this.setState({ value: 0 });
        } else if (
            this.props.spHeight.filter(
                check => check.spWeight === 'Two'
            ).length > 0
        ) {
            this.setState({ value: 1 });
        }
    }

    handleChange = (event, value) => {
        console.log('handleChange -value', value);

        this.setState({ value });
    };

    handleSportsRadioValueChange = (category, value) => {
        console.log('handleSportsRadioValueChange -category', category);

        console.log('handleSportsRadioValueChange -value', value);
        this.setState({ spLength: value });
    };

    render() {
        const { classes, data } = this.props;

        let udVal = '';
        let starVal = '';
        udVal = data.udVals ? data.udVals[0].number : '';
        starVal = data.starVals ? data.starVals[0].number : '';

        const { canEdit, value } = this.state;
        const { spHeight } = this.state;

        return (
            <div>
                <AppBar
                    className={classes.benchmarkTabHeader}
                    position="static"
                    color="default"
                >
                    <Tabs
                        onChange={this.handleChange}
                        variant="scrollable"
                        scrollButtons="on"
                        indicatorColor="primary"
                        textColor="primary"
                        style={{ display: 'block' }}
                        classes={{
                            indicator: classes.tabsIndicator,
                            scrollButtons: classes.MuiPrivateTabScrollButton,
                        }}
                    >
                        <Tab
                            style={{
                                display:
                                    this.state.spHeight.filter(
                                        check =>
                                            check.spWeight === 'One'
                                    ).length === 0
                                        ? 'none'
                                        : '',
                                color: value == 0 ? '#1976D2' : '#66696C',
                            }}
                            label={`Groups (${
                                this.state.spHeight.filter(
                                    check =>
                                        check.spWeight === 'One'
                                ).length
                            })`}
                            icon={
                                <FontAwesomeIcon style={{ display: 'block' }} />
                            }
                            classes={{
                                root: classes.tabRoot,
                                selected: classes.tabSelected,
                                wrapper: classes.alignment,
                            }}
                        />
                        <Tab
                            style={{
                                display:
                                    this.state.spHeight.filter(
                                        check =>
                                            check.spWeight ===
                                            'Two'
                                    ).length === 0
                                        ? 'none'
                                        : '',
                                color: value == 1 ? '#1976D2' : '#66696C',
                            }}
                            label={`Two (${
                                this.state.spHeight.filter(
                                    check =>
                                        check.spWeight ===
                                        'Two'
                                ).length
                            })`}
                            icon={
                                <FontAwesomeIcon style={{ display: 'block' }} />
                            }
                            classes={{
                                root: classes.tabRoot,
                                selected: classes.tabSelected,
                                wrapper: classes.alignment,
                            }}
                        />

                    </Tabs>
                </AppBar>
                {value === 0 && (
                    <TabContainer>
                        <div>
                            {' '}
                            <FormControl
                                component="fieldset"
                                className={classes.formControl}
                            >
                                <FormLabel component="legend" />
                                <RadioGroup
                                    aria-label="Gender"
                                    name="gender1"
                                    className={classes.one}
                                    value={this.state.spLength}
                                    onChange={e => {
                                        this.setState({
                                            spLength: e.target.value,
                                        });
                                    }}
                                >
                                    {this.state.spHeight
                                        .filter(
                                            check =>
                                                check.spWeight ===
                                                'One'
                                        )
                                        .map((radio, radioIndex) => {
                                            return (
                                                <FormControlLabel
                                                    key={radioIndex}
                                                    value={radio.value}
                                                    control={<Radio />}
                                                    label={radio.label}
                                                    classes={{
                                                        label:
                                                            classes.checkboxLabel,
                                                    }}
                                                />
                                            );
                                        })}
                                    )}
                                </RadioGroup>
                            </FormControl>
                            <div className="tiger-button-container">
                                <Button
                                    variant="outlined"
                                    color="primary"
                                    size="small"
                                    className="tiger-button-upload"
                                >
                                    ghsd jkjkjk
                                </Button>
                            </div>
                            <Drawer
                                style={{ width: 500 }}
                                anchor="right"
                                open={this.state.right}
                            >
                                <div tabIndex={0} role="button"></div>
                            </Drawer>
                        </div>
                    </TabContainer>
                )}
                {value === 1 && (
                    <TabContainer>
                        <div>
                            <div>
                                <FormControl
                                    component="fieldset"
                                    className={classes.formControl}
                                >
                                    <RadioGroup
                                        aria-label="Gender"
                                        name="gender1"
                                        className={classes.one}
                                        value={this.state.spLength}
                                        onChange={e => {
                                            this.setState({
                                                spLength:
                                                    e.target.value,
                                            });
                                        }}
                                    >
                                        {this.state.spHeight
                                            .filter(
                                                check =>
                                                    check.spWeight ===
                                                    'Two'
                                            )
                                            .map((radio, radioIndex) => {
                                                return (
                                                    <FormControlLabel
                                                        key={radioIndex}
                                                        value={radio.label}
                                                        control={<Radio />}
                                                        label={radio.label}
                                                        classes={{
                                                            label:
                                                                classes.checkboxLabel,
                                                        }}
                                                    />
                                                );
                                            })}
                                    </RadioGroup>
                                </FormControl>

                                <div className="tiger-button-container">
                                    <Button
                                        variant="outlined"
                                        color="primary"
                                        size="small"
                                        className="tiger-button-upload"
                                    >
                                        ghsd jkjkjk
                                    </Button>
                                </div>
                            </div>
                        </div>
                    </TabContainer>
                )}

            </div>
        );
    }
}

export default withStyles(styles)(SportsExpansion);

///////////////////////////////功能組件碼

import React, { Fragment, useState, useEffect, Component } from 'react';
import styles from './styles';
import { withStyles } from '@material-ui/core/styles';
import classnames from 'classnames';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import IconButton from '@material-ui/core/IconButton';
import Button from '@material-ui/core/Button';
import ExpansionPanel from '@material-ui/core/ExpansionPanel';
import ExpansionPanelSummary from '@material-ui/core/ExpansionPanelSummary';
import ExpansionPanelDetails from '@material-ui/core/ExpansionPanelDetails';
import Typography from '@material-ui/core/Typography';

import Drawer from '@material-ui/core/Drawer';
import AppBar from '@material-ui/core/AppBar';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';

import Radio from '@material-ui/core/Radio';
import RadioGroup from '@material-ui/core/RadioGroup';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import FormControl from '@material-ui/core/FormControl';
import FormLabel from '@material-ui/core/FormLabel';

import Checkbox from '@material-ui/core/Checkbox';
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import dataStyles from '../../../../styles.css';

function TabContainer(props) {
    return (
        <Typography component="div" style={{ padding: 8 * 3 }}>
            {props.children}
        </Typography>
    );
}

const radioValues = [
    {
        label: 'Select All Providers for This Category',
        value: 'PRO',
    },
];

//class SportsExpansion extends Component {
const SportsExpansion = (props) => {



    const [value, setValue] = useState(0);
    const [spHeight, setspHeight] = useState([]);
    const [spLength, setspLength] = useState('');


    // const { classes, data } = this.props;
    const { classes, data } = props;


    let udVal = '';
    let starVal = '';
    udVal = data.udVals ? data.udVals[0].number : '';
    starVal = data.starVals ? data.starVals[0].number : '';

    // const { canEdit, value } = this.state;
    // const { spHeight } = this.state;




    useEffect(() => {
        // code to run on component mount
                console.log("useEffect setspHeight--->", setspHeight);


        //this.setState({ spHeight: this.props.spHeight });
        setspHeight(spHeight);

        if (
            spHeight.filter(
                check => check.spWeight === 'One'
            ).length > 0
        ) {
            useState({ value: 0 });
        } else if (
            spHeight.filter(
                check => check.spWeight === 'Two'
            ).length > 0
        ) {
            useState({ value: 1 });
        } 
    }, [])

    //handleChange = (event, value) => {
    const handleChange = (event, value) => {

        console.log('handleChange -value', value);

        useState({ value });
    };

    // handleSportsRadioValueChange = (category, value) => {
    const handleSportsRadioValueChange = (category, value) => {

        console.log('handleSportsRadioValueChange -category', category);

        console.log('handleSportsRadioValueChange -value', value);
        useState({ spLength: value });
    };

    return (
        <div>
            <AppBar
                className={classes.benchmarkTabHeader}
                position="static"
                color="default"
            >
                <Tabs
                    onChange={this.handleChange}
                    variant="scrollable"
                    scrollButtons="on"
                    indicatorColor="primary"
                    textColor="primary"
                    style={{ display: 'block' }}
                    classes={{
                        indicator: classes.tabsIndicator,
                        scrollButtons: classes.MuiPrivateTabScrollButton,
                    }}
                >
                    <Tab
                        style={{
                            display:
                            //this.state.spHeight.filter(
                            spHeight.filter(
                                check =>
                                    check.spWeight === 'One'
                            ).length === 0
                                ? 'none'
                                : '',
                            color: value == 0 ? '#1976D2' : '#66696C',
                        }}
                        label={`Groups (${
                            //this.state.spHeight.filter(
                            spHeight.filter(
                                check =>
                                    check.spWeight === 'One'
                            ).length
                            })`}
                        icon={
                            <FontAwesomeIcon style={{ display: 'block' }} />
                        }
                        classes={{
                            root: classes.tabRoot,
                            selected: classes.tabSelected,
                            wrapper: classes.alignment,
                        }}
                    />
                    <Tab
                        style={{
                            display:
                            //this.state.spHeight.filter(
                            spHeight.filter(
                                check =>
                                    check.spWeight ===
                                    'Two'
                            ).length === 0
                                ? 'none'
                                : '',
                            color: value == 1 ? '#1976D2' : '#66696C',
                        }}
                        label={`Two (${
                            //this.state.spHeight.filter(
                            spHeight.filter(
                                check =>
                                    check.spWeight ===
                                    'Two'
                            ).length
                            })`}
                        icon={
                            <FontAwesomeIcon style={{ display: 'block' }} />
                        }
                        classes={{
                            root: classes.tabRoot,
                            selected: classes.tabSelected,
                            wrapper: classes.alignment,
                        }}
                    />

                </Tabs>
            </AppBar>
            {value === 0 && (
                <TabContainer>
                    <div>
                        {' '}
                        <FormControl
                            component="fieldset"
                            className={classes.formControl}
                        >
                            <FormLabel component="legend" />
                            <RadioGroup
                                aria-label="Gender"
                                name="gender1"
                                className={classes.one}
                                value={//this.state.spLength
                                    spLength}
                                onChange={e => {
                                    useState({
                                        spLength: e.target.value,
                                    });
                                }}
                            >
                                {//this.state.spHeight
                                    spHeight
                                        .filter(
                                        check =>
                                            check.spWeight ===
                                            'One'
                                        )
                                        .map((radio, radioIndex) => {
                                            return (
                                                <FormControlLabel
                                                    key={radioIndex}
                                                    value={radio.value}
                                                    control={<Radio />}
                                                    label={radio.label}
                                                    classes={{
                                                        label:
                                                        classes.checkboxLabel,
                                                    }}
                                                />
                                            );
                                        })}
                                )}
                                </RadioGroup>
                        </FormControl>
                        <div className="tiger-button-container">
                            <Button
                                variant="outlined"
                                color="primary"
                                size="small"
                                className="tiger-button-upload"
                            >
                                ghsd jkjkjk
                                </Button>
                        </div>
                        {/*<Drawer
                            style={{ width: 500 }}
                            anchor="right"
                            open={

                                //this.state.right
                                right}
                        >
                            <div tabIndex={0} role="button"></div>
                        </Drawer>*/}
                    </div>
                </TabContainer>
            )}
            {value === 1 && (
                <TabContainer>
                    <div>
                        <div>
                            <FormControl
                                component="fieldset"
                                className={classes.formControl}
                            >
                                <RadioGroup
                                    aria-label="Gender"
                                    name="gender1"
                                    className={classes.one}
                                    value={//this.state.spLength
                                        spLength}
                                    onChange={e => {
                                        useState({
                                            spLength:
                                            e.target.value,
                                        });
                                    }}
                                >
                                    {//this.state.spHeight
                                        spHeight
                                            .filter(
                                            check =>
                                                check.spWeight ===
                                                'Two'
                                            )
                                            .map((radio, radioIndex) => {
                                                return (
                                                    <FormControlLabel
                                                        key={radioIndex}
                                                        value={radio.label}
                                                        control={<Radio />}
                                                        label={radio.label}
                                                        classes={{
                                                            label:
                                                            classes.checkboxLabel,
                                                        }}
                                                    />
                                                );
                                            })}
                                </RadioGroup>
                            </FormControl>

                            <div className="tiger-button-container">
                                <Button
                                    variant="outlined"
                                    color="primary"
                                    size="small"
                                    className="tiger-button-upload"
                                >
                                    ghsd jkjkjk
                                    </Button>
                            </div>
                        </div>
                    </div>
                </TabContainer>
            )}

        </div>
    );


}

export default withStyles(styles)(SportsExpansion);

您必須在調用useState({ value: 1 });地方進行替換useState({ value: 1 }); 設置為setValue(value)

您使用useState錯誤。 useState替換狀態對象。 數組中的第一個值是您可以在組件中調用的值。 數組中的第二個值替換this.setState並設置狀態實例的值。 因此,如果您具有以下條件,請使用useState掛鈎:

const [value, setValue] = useState(0);

您將在組件中使用value來引用此狀態實例。 然后,您將使用setValue設置此狀態實例的值。 因此,要將value設置為2,可以執行setValue(2)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM