使用React挂钩从用户选择中获取数据

时间:2020-04-29 19:24:01

标签: reactjs async-await react-hooks use-effect use-state

所以我对React Hooks还是很陌生,似乎无法弄清楚。我想做的是让用户从下拉菜单中选择一个项目,并在用户每次选择新项目时获取数据。当用户从下拉菜单中选择一项时,“ selectedState”变量将更新,但是我的useEffect函数必须获取数据两次,然后才能获取当前“ selectedState”的正确数据。我曾考虑过将下拉列表分为自己的组件,然后将数据传递到另一个组件以获取数据,但是我不知道这是否真的可以解决问题。

这是我的代码:

    const initialState = () => {
        return {
            loading: true,
            post: '',
            error: ''
        }
    }

function reducer(state, action) {
        switch (action.type) {
            case 'fetch_success':
                return {
                    loading: false,
                    post: action.payload,
                    error: ''
                }
            case 'fetch_error':
                return {
                    loading: false,
                    post: {},
                    error: 'Something went wrong'
                }
            default:
                return state
        }
    }

    export default () => {
        const [state, dispatch] = useReducer(reducer, initialState);
        const [selectedState, getSelectedState] = useState('');
        const dropDownList = ['Alabama', 'Alaska', 'American Samoa', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'District of Columbia', 'Florida', 'Georgia', 'Guam', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Minor Outlying Islands', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Northern Mariana Islands', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Puerto Rico', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'U.S. Virgin Islands', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming']


        const dropDown =
            <select
                id="state-dropdown"
                onChange={e => getSelectedState(e.target.value)}
                value={selectedState}
                disabled={!dropDownList.length}>
                <option>Choose State</option>
                {dropDownList.map((item) => <option key={item} value={item}>{item}</option>)}
            </select >


        useEffect(() => {
            async function fetchData() {
                const response = await fetch((`https://covid-19-statistics.p.rapidapi.com/reports?&iso=USA&region_name=US&date=2020-04-16&q=US%20${selectedState}`), {
                    "method": "GET",
                    "headers": {
                        "x-rapidapi-host": "covid-19-statistics.p.rapidapi.com",
                        "x-rapidapi-key": "8eb0a7c674msh30916dd1116d55cp1700f5jsn651eb7015384"
                    }
                });
                dispatch({ type: 'fetch_success', payload: response.json() });
            }
            fetchData();
        }, [selectedState, dispatch]);

        {console.log(state)}


        return (
            <div>
                <CardHeader>- State -</CardHeader>
                <Card>
                    <label>
                        {dropDown}
                    </label>
                </Card>
            </div>
        )
    }

0 个答案:

没有答案