简体   繁体   中英

React MenuItem event.target.value not working in one, but works for the other MenuItem

I have two MenuItem drop down menus. The first is for selecting between two items (not working) and the second drop down menu has a list of years, which is working.

The following are the functions that I have created to capture the event.target.value for each of them:

 handleYrChange = (event) => {
    console.log('handleYrChange: ' + event.target.value);
    this.setState({ data: [] });
    getPartIdUpperSa(event.target.value).subscribe((res) => {
        this.setState({ data: res });
        this.setState({ isLoading: false });
    });
    this.props.isLoading ? this.setState({ isLoading: false }) : this.setState({ isLoading: true });
    this.setState({ yrValue: event.target.value });
    this.onCloseYr();
}

handleSaChange = (event) => {
    console.log('handleSaChange: ' + event.target.value);

    if(event.target.value === 'notSa') {
        this.setState({ isPartIdUpperSa: false });
    } else {
        this.setState({ isPartIdUpperSa: true });        
    }

    setBaseUrl(event.target.value);
    this.setState({ saValue: event.target.value });
    this.onCloseSa();
}

handleYrClick = (event) => {
    this.setState({ yrAnchorEl: event.target })
    this.setState({ yrOpen: true });
}

handleSaClick = (event) => {
    this.setState({ saAnchorEl: event.target })
    this.setState({ saOpen: true });
}

The following is a screen shot of when I have tried to click on the items. As you can see, the drop down for years is working as expected, yet the other is capturing "0"

控制台日志结果的屏幕截图

The following is the full component, along with the service that it is subscribed:

First the component:

    import React from "react";
    import { FormGroup, FormControl, Button, Menu, MenuItem } from '@material-ui/core';
    import MUIDataTable from "mui-datatables";
    import { MuiThemeProvider } from '@material-ui/core/styles';
    import { getPartIdUpperSa } from '../services/part-id-upper-sa-service';
    import { setBaseUrl } from '../services/part-id-upper-sa-service'
    import theme from '../theme';

    export default class ParIdUpperSaComponent extends React.Component {
        state = {
            data: [],
            Header: [],
            totalCount: 10,
            options: {
                pageSize: 16,
                page: 0,
                filterType: "dropdown",
                selectableRows: false,
                responsive: "scroll",
                resizableColumns: true,
                className: this.name,
                textLabels: {
                    body: {
                        noMatch: this.props.isLoading ?
                            '' :
                            'Please wait while processing...',
                    },
                },
            },
            divAnchorEl: null,
            yrValue: '2020',
            yrOpen: false,
            yrAnchorEl: null,
            yrs: [],
            saValue: 'sa',
            saOpen: false,
            saAnchorEl: null,
            sa: ["sa","notSa"],
            isLoading: true,
            isPartIdUpperSa: true
        }

        componentDidMount() {
            // create array of years for the past 18 years
            const currentYr = new Date().getFullYear();
            for(let x = 0; x < 18; x++) {
                this.state.yrs.push(currentYr - x );
            }

            this.subscription = getPartIdUpperSa().subscribe((res) => {
                this.setState({ data: res });

                this.props.isLoading ? this.setState({ textLabels: '' }) : this.setState({ textLabels: 'Please wait while processing...' });
                this.setState({ isLoading: false });
                this.setState({ Header: [
                    {
                        label: "Part ID",
                        name: 'part_id_upper',
                        options: {
                            className: 'first-col'
                        }
                    },
                    {
                        label: "Seq",
                        name: 'sequence',
                        options: {
                            className: 'sec-col'
                        }
                    },
                    {
                        label: "Qty",
                        name: 'quantity',
                        options: {
                            className: 'sm-col'
                        }
                    },
                    {
                        label: "Dt Orig",
                        name: 'date_originated',
                        options: {
                            className: 'mid-col'
                        }
                    },
                    {
                        label: "Div",
                        name: 'code_division',
                        options: {
                            className: 'sm-col'
                        }
                    },
                ]});
                this.setState({
                    totalCount: Math.ceil(this.state.data.length / this.state.pageSize)
                });
            })
        }

        componentWillUnmount() {
            // unsubscribe to ensure no memory leaks
            this.subscription.unsubscribe();
        }

        handleYrChange = (event) => {
            console.log('handleYrChange: ' + event.target.value);
            // this.setState({value: event.target.value ? event.target.value : ''});
            this.setState({ data: [] });
            getPartIdUpperSa(event.target.value).subscribe((res) => {
                this.setState({ data: res });
                this.setState({ isLoading: false });
            });
            this.props.isLoading ? this.setState({ isLoading: false }) : this.setState({ isLoading: true });
            this.setState({ yrValue: event.target.value });
            this.onCloseYr();
        }

        handleSaChange = (event) => {
            console.log('handleSaChange: ' + event.target.value);

            if(event.target.value === 'notSa') {
                this.setState({ isPartIdUpperSa: false });
            } else {
                this.setState({ isPartIdUpperSa: true });        
            }

            setBaseUrl(event.target.value);
            this.setState({ saValue: event.target.value });
            this.onCloseSa();
        }

        handleYrClick = (event) => {
            this.setState({ yrAnchorEl: event.target })
            this.setState({ yrOpen: true });
        }

        handleSaClick = (event) => {
            this.setState({ saAnchorEl: event.target })
            this.setState({ saOpen: true });
        }

        onCloseYr = () => {
            this.setState({ yrOpen: false });
        }

        onCloseSa = () => {
            this.setState({ saOpen: false });
        }

        render() {
            let arrayofSa = this.state.sa;
            let saDropDown = arrayofSa.map((sa) => 
                <MenuItem onClick={(event) => this.handleSaChange(event)} value={sa} key={sa}>
                    {sa}
                </MenuItem>              
            );
            let arrayOfYrs = this.state.yrs;
            let yrDropDown = arrayOfYrs.map((yrs) =>
                <MenuItem onClick={(event) => this.handleYrChange(event)} value={yrs} key={yrs}>
                    {yrs}
                </MenuItem>           
            );
            return (
                <div>
                <MuiThemeProvider theme={theme}>
                    <FormGroup column='true'>
                        <FormControl>
                            <Button aria-controls="simple-menu" aria-haspopup="true" onClick={this.handleSaClick}>
                                Select Sa or NotToSa
                            </Button>
                            <Menu id="sa-menu" open={this.state.saOpen}
                                anchorEl={this.state.saAnchorEl}  onClose={this.onCloseSa}
                                defaultValue={this.state.saValue ? this.state.saValue : ''} >
                                    {saDropDown}
                            </Menu>
                            <Button aria-controls="simple-menu" aria-haspopup="true" onClick={this.handleYrClick}>
                                Select Year
                            </Button>
                            <Menu id="yrs-menu" open={this.state.yrOpen}
                                anchorEl={this.state.yrAnchorEl}  onClose={this.onCloseYr}
                                defaultValue={this.state.yrValue ? this.state.yrValue : ''} >
                                    {yrDropDown}
                            </Menu>
                        </FormControl>
                    </FormGroup>
                </MuiThemeProvider>

                    {this.state.isLoading ? <img src="ajax-loader.gif" alt="loading gif" /> : ''}
                    <MUIDataTable
                    title="Part ID Upper Sa / Not Sa Report"
                    data={ this.state.data }
                    columns={ this.state.Header }
                    options={ this.state.options }
                    />
                </div>
            );
        }
        }

The following is the service:

    import { ajax } from "rxjs/ajax";
    import { Observable } from "rxjs";

    let base_url = 'https://localhost:5001/PartIdUpperSa';

    export const getBaseUrl = () => {
        return base_url;
    }

    export const setBaseUrl = (param) => {
        console.log("from within setBaseUrl: " + param);
        if(param === 'notSa') {
            base_url = 'https://localhost:5001/PartIdUpperNotSa';
        } else {
            base_url = 'https://localhost:5001/PartIdUpperSa';
        }
    }

    let state = {
        data: []
    }

    export const getPartIdUpperSa = (yr) => {
        return new Observable(observe => {
            let mYr = new Date().getFullYear();
            let tempYr = (yr)? yr : mYr;
            state.data = ajax
            .get(base_url + "/" + tempYr)
            .subscribe(resu => {
                state.data = resu.response ;
                // console.log("from within getPartIdUpperSa: " + JSON.stringify(resu.response));
                observe.next(resu.response);
            });
        });
    }

As usual, thanks in advance

I was able to find a work around. If someone could explain why this works, then I would appreciate it.

The component now uses numbers instead of characters in the array called "sa," which made it function as expected.

I used this:

sa: ["1","2"],

instead of this:

sa: ["sa","notSa"],

And it worked, the following is the complete component:

    import React from "react";
    import { FormGroup, FormControl, Button, Menu, MenuItem } from '@material-ui/core';
    import MUIDataTable from "mui-datatables";
    import { MuiThemeProvider } from '@material-ui/core/styles';
    import { getPartIdUpperSa } from '../services/part-id-upper-sa-service';
    import { setBaseUrl } from '../services/part-id-upper-sa-service'
    import theme from '../theme';

    export default class ParIdUpperSaComponent extends React.Component {
        state = {
            data: [],
            Header: [],
            totalCount: 10,
            options: {
                pageSize: 16,
                page: 0,
                filterType: "dropdown",
                selectableRows: false,
                responsive: "scroll",
                resizableColumns: true,
                className: this.name,
                textLabels: {
                    body: {
                        noMatch: this.props.isLoading ?
                            '' :
                            'Please wait while processing...',
                    },
                },
            },
            divAnchorEl: null,
            yrValue: '2020',
            yrOpen: false,
            yrAnchorEl: null,
            yrs: [],
            saValue: '1',
            saOpen: false,
            saAnchorEl: null,
            sa: ["1","2"],
            isLoading: true,
            isPartIdUpperSa: true
        }

        componentDidMount() {
            // create array of years for the past 18 years
            const currentYr = new Date().getFullYear();
            for(let x = 0; x < 18; x++) {
                this.state.yrs.push(currentYr - x );
            }

            this.subscription = getPartIdUpperSa().subscribe((res) => {
                this.setState({ data: res });

                this.props.isLoading ? this.setState({ textLabels: '' }) : this.setState({ textLabels: 'Please wait while processing...' });
                this.setState({ isLoading: false });
                this.setState({ Header: [
                    {
                        label: "Part ID",
                        name: 'part_id_upper',
                        options: {
                            className: 'first-col'
                        }
                    },
                    {
                        label: "Seq",
                        name: 'sequence',
                        options: {
                            className: 'sec-col'
                        }
                    },
                    {
                        label: "Qty",
                        name: 'quantity',
                        options: {
                            className: 'sm-col'
                        }
                    },
                    {
                        label: "Dt Orig",
                        name: 'date_originated',
                        options: {
                            className: 'mid-col'
                        }
                    },
                    {
                        label: "Div",
                        name: 'code_division',
                        options: {
                            className: 'sm-col'
                        }
                    },
                ]});
                this.setState({
                    totalCount: Math.ceil(this.state.data.length / this.state.pageSize)
                });
            })
        }

        componentWillUnmount() {
            // unsubscribe to ensure no memory leaks
            this.subscription.unsubscribe();
        }

        handleYrChange = (event) => {
            console.log('handleYrChange: ' + event.target.value);
            this.setState({ data: [] });
            getPartIdUpperSa(event.target.value).subscribe((res) => {
                this.setState({ data: res });
                this.setState({ isLoading: false });
            });
            this.props.isLoading ? this.setState({ isLoading: false }) : this.setState({ isLoading: true });
            this.setState({ yrValue: event.target.value });
            this.onCloseYr();
        }

        handleSaChange = (event) => {
            console.log('handleSaChange: ' + event.target.value);

            if(event.target.value === '2') {
                this.setState({ isPartIdUpperSa: false });
            } else {
                this.setState({ isPartIdUpperSa: true });        
            }

            setBaseUrl(event.target.value);
            this.setState({ saValue: event.target.value });
            this.onCloseSa();
        }

        handleYrClick = (event) => {
            this.setState({ yrAnchorEl: event.target })
            this.setState({ yrOpen: true });
        }

        handleSaClick = (event) => {
            this.setState({ saAnchorEl: event.target })
            this.setState({ saOpen: true });
        }

        onCloseYr = () => {
            this.setState({ yrOpen: false });
        }

        onCloseSa = () => {
            this.setState({ saOpen: false });
        }

        render() {
            let arrayofSa = this.state.sa;
            let saDropDown = arrayofSa.map((sa) => 
                <MenuItem onClick={(event) => this.handleSaChange(event)} value={sa} key={sa}>
                    {sa}
                </MenuItem>              
            );
            let arrayOfYrs = this.state.yrs;
            let yrDropDown = arrayOfYrs.map((yrs) =>
                <MenuItem onClick={(event) => this.handleYrChange(event)} value={yrs} key={yrs}>
                    {yrs}
                </MenuItem>           
            );
            return (
                <div>
                <MuiThemeProvider theme={theme}>
                    <FormGroup column='true'>
                        <FormControl>
                            <Button aria-controls="simple-menu" aria-haspopup="true" onClick={this.handleSaClick}>
                                Select Sa or NotToSa
                            </Button>
                            <Menu id="sa-menu" open={this.state.saOpen}
                                anchorEl={this.state.saAnchorEl}  onClose={this.onCloseSa}
                                defaultValue={this.state.saValue ? this.state.saValue : ''} >
                                    {saDropDown}
                            </Menu>
                            <Button aria-controls="simple-menu" aria-haspopup="true" onClick={this.handleYrClick}>
                                Select Year
                            </Button>
                            <Menu id="yrs-menu" open={this.state.yrOpen}
                                anchorEl={this.state.yrAnchorEl}  onClose={this.onCloseYr}
                                defaultValue={this.state.yrValue ? this.state.yrValue : ''} >
                                    {yrDropDown}
                            </Menu>
                        </FormControl>
                    </FormGroup>
                </MuiThemeProvider>

                    {this.state.isLoading ? <img src="ajax-loader.gif" alt="loading gif" /> : ''}
                    <MUIDataTable
                    title="Part ID Upper Sa / Not Sa Report"
                    data={ this.state.data }
                    columns={ this.state.Header }
                    options={ this.state.options }
                    />
                </div>
            );
        }
    }

The following is the service that the component is subscribed to it:

    import { ajax } from "rxjs/ajax";
    import { Observable } from "rxjs";

    let base_url = 'https://localhost:5001/PartIdUpperSa';

    export const getBaseUrl = () => {
        return base_url;
    }

    export const setBaseUrl = (param) => {
        console.log("from within setBaseUrl: " + param);
        if(param == '1') {
            base_url = 'https://localhost:5001/PartIdUpperSa';
        } else {
            base_url = 'https://localhost:5001/PartIdUpperNotSa';
        }
    }

    let state = {
        data: []
    }

    export const getPartIdUpperSa = (yr) => {
        return new Observable(observe => {
            let mYr = new Date().getFullYear();
            let tempYr = (yr)? yr : mYr;
            state.data = ajax
            .get(base_url + "/" + tempYr)
            .subscribe(resu => {
                state.data = resu.response ;
                observe.next(resu.response);
            });
        });
    }

Once more, if someone could explain why numbers work with event.target.value and characters do not, then I would appreciate it.

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