如何在react-country-region-selector中使用useReducer?

问题描述

我将react-country-region-selector与useState一起使用,它工作良好,并通过选择国家/地区来更新下拉列表,代码如下:

import React,{ useState } from 'react';

const App = () => {
  const [country,setCountry] = useState('');
  
  const handleCountryChange = (country) => {
    setCountry(country);
  }
  
  return (
    <CountryDropdown
        value={country}
        onChange={handleCountryChange}
        />
  )
}

现在我正尝试使用useReducer,因为我要更新多个状态。但是我的代码不再与react-country-region-selector一起使用,代码如下:

import React,{ useReducer } from 'react';

const App = () => {

  const reducer = (state,action) => {
    switch (action.type) {
      case 'setCountry':
        return {
          country: state.country
        }
    }
  }
  
  const handleCountryChange = (country) => {
    dispatch({type: 'setCountry'});
  }
  
  return (
    <CountryDropdown
        value={country}
        onChange={handleCountryChange}
        />
  )

}

选择国家/地区后,下拉列表将不再更新。这种情况下useReducer有什么问题?如何使用useReducer更新国家/地区选择?

解决方法

您可以在此处阅读有关useReducer的更多详细信息:https://reactjs.org/docs/hooks-reference.html#usereducer

您的代码应为:

import React,{ useReducer } from 'react';

const App = () => {

    const reducer = (state,action) => {
        switch (action.type) {
            case 'setCountry':
                return {
                    ...state,country: action.country
                }
        }
    }

    const [state,dispatch ]=  useReducer(reducer,{country: ''});

    const handleCountryChange = (country) => {
        dispatch({type: 'setCountry',country});
    }

    return (
        <CountryDropdown
            value={state.country}
            onChange={handleCountryChange}
        />
    )
}