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

How to use useReducer in react-country-region-selector?

我将 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}
        />
    )
}