Как отфильтровать данные в реагируемой таблице из данных в выпадающем списке - PullRequest
0 голосов
/ 07 июля 2019

Я новичок в реакцииJS.

Я выбираю данные для загрузки сетки "populateGrid ()" и другой для заполнения раскрывающегося списка этапами "populateDropDown ()"

const optionsStages = []

class CommentsTableComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            isLoaded: false,
            filterDescription: '',
            projectID: '',
            xtoken: '', 
        };

      this.populateGrid = this.populateGrid.bind(this);
        this.populateDropDown = this.populateDropDown.bind(this);
        localStorage.setItem("projectID", this.props.match.params.projectID)
    }
    componentDidMount() {
        this.populateGrid();
        this.populateDropDown();
    }

    populateGrid() {
        const tokenvalue = document.getElementsByName("__RequestVerificationToken")[0].value;
        projectID = this.props.match.params.projectID;

        let config = {
            method: 'POST',
            body: JSON.stringify({ projectID: projectID }),
            headers: {
                "XSRF-TOKEN": tokenvalue,
                "Content-Type": "application/json; charset=utf-8"
            }
        }

        fetch('/WebServices/GetThreadsByProjectID?handler=Send', config)
            .then(res => res.json())
            .then(response =>
                this.setState({
                    data: response,
                    projectID: projectID
                }, () => {
                    console.log(this.state.data[0]);
                })
            )
            .catch(error => console.error('Error:', error));
    }

    populateDropDown() {
        const tokenvalue = document.getElementsByName("__RequestVerificationToken")[0].value;
        projectID = localStorage.getItem("projectID");

        let config = {
            method: 'POST',
            body: JSON.stringify({ projectID: projectID }),
            headers: {
                "XSRF-TOKEN": tokenvalue,
                "Content-Type": "application/json; charset=utf-8"
            }
        }

        fetch('/WebServices/GetStagesByProjectID?handler=Send', config)
        .then(res => res.json())
        .then(response => {
            const allObj = { value: 'all', label: 'All' };
            var newStages = Array.from(response, obj => {
                var rObj = { value: obj.id, label: obj.stage };
                return rObj;
            });
            newStages.push(allObj);
            this.setState({
                optionsStages: newStages,
                projectID: projectID
            }, () => {
                console.log(this.state.optionsStages);
            })
        })
        .catch(error => console.error('Error:', error));
    }

    handleDropDownChange(event) {
        console.log("event:", event)
        this.setState({ value: event.target.value });
        console.log("propreities:", this.state)
    }

Затем рендер:

render() {
    const { data } = this.state;
    const allObj = { value: 'all', label: 'All' };
    return (
        <div>
            <div className="grid-wrapper">
                <div className="toolbar-sections comments">
                        <Select
                            id="selectStage"
                            getOptionLabel={(option) => 'Stage: ' + option.label}
                            className="toolbar-select"
                            options={this.state.optionsStages}
                            onChange={(value) => { this.handleDropDownChange(value, 'selectedStage') }}
                            placeholder="Stages"
                            isSearchable={false}
                            defaultValue={allObj}
                        />
                </div>
                <ReactTable
                    filtered={this.state.filtered}
                    defaultFilterMethod={(filter, row) =>
                        String(row[filter.id]) === filter.value}
                    data={data}
                    onFilteredChange={this.onFilteredChange.bind(this)}
                    columns={[
                        {
                            Header: "Author",
                            id: "author",
                            accessor: "author",
                            width: 170,
                            Cell: row => {
                                return (
                                    <span>
                                        {row.value}
                                    </span>
                                );
                            }
                        },
                        {
                            Header: "Subject",
                            accessor: "subject",
                            Cell: row => (
                                <span>
                                    <span><a href="#">{row.value}...</a></span>
                                </span>
                            )
                        },
                        {
                            Header: "Stage",
                            accessor: "stage",
                            width: 150
                        }
                    ]}
                    defaultPageSize={10}
                    className="-highlight"
                />
                <br />

            </div>
        </div>
    );
    }
}
export default withRouter(CommentsTableComponent);

Я могу загрузить раскрывающийся список с данными, возвращенными из populateDropDown (), но я бы хотел фильтровать по этапам (3-я строка).

Я смотрел на другие примеры, но разница была в том, что я загружал выпадающие данные из базы данных.

...