如何在路线中传递道具?

时间:2020-08-08 12:26:45

标签: reactjs react-redux

我在Country.js中有选定的国家。我想做的就是将此国家/地区传递给Home.js,并在用户单击按钮时呈现Home.js。

App.js

const App = () => {
  return (
    <BrowserRouter>
      <Switch>
        <Route exact path="/" component={Country} />
        <Route path="/home" component={Home} />
      </Switch>
    </BrowserRouter>
  );
};

Country.js

return (
    <div className="container">
      <label htmlFor="country">Country</label>
      <select name="country" id="country" onChange={handleSelect}>
        <option value="-1">--Country--</option>
        <option value="in">India</option>
        <option value="jp">Japan</option>
        <option value="us">USA</option>
        <option value="br">Brazil</option>
        <option value="ch">China</option>
        <option value="sr">Sri lanka</option>
      </select>
      <Link to="/home">
        <button type="submit">Proceed</button>
      </Link>
    </div>
  );

1 个答案:

答案 0 :(得分:2)

要将所选国家/地区传递到Home,需要在Home之上的一个级别上管理其状态。

const App = () => {
  const [country, setCountry] = useState();

  return (
    <BrowserRouter>
      <Switch>
        <Route
          exact
          path="/"
          render={(props) => (
            <Country
              {...props} // pass through router props if needed
              country={country}
              onChangeCountry={setCountry}
            />
          )}
        />
        <Route
          path="/home"
          render={(props) => (
            <Home
              {...props} // pass through router props if needed
              country={country}
            />
          )}
        />
      </Switch>
    </BrowserRouter>
  );
};

Country.js:

const Country = ({country, onChangeCountry}) => {
  const handleSelect = useCallback(
    (event) => {
      if (typeof onChangeCountry === 'function') {
        onChangeCountry(event.target.value);
      }
    },
    [onChangeCountry]
  );

  return (
    <div className="container">
      <label htmlFor="country">Country</label>
      <select
        name="country"
        id="country"
        value={country}
        onChange={handleSelect}
      >
        <option value="-1">--Country--</option>
        <option value="in">India</option>
        <option value="jp">Japan</option>
        <option value="us">USA</option>
        <option value="br">Brazil</option>
        <option value="ch">China</option>
        <option value="sr">Sri lanka</option>
      </select>
      <Link to="/home">
        <button type="submit">Proceed</button>
      </Link>
    </div>
  );
};