reactjs 如何在react中更新子组件中的变量?

brvekthn  于 2023-01-04  发布在  React
关注(0)|答案(1)|浏览(129)

我有3个组件,父组件是App,子组件是SearchFlight和FoundFlight。
我正在尝试将应用程序从SearchFlights(通过其flightInput属性)接收的字符串值传递给FoundFlight。
然后,我希望FoundFlight在每次更改该值时将该值赋给一个局部变量。
下面是我在App.js中的代码:

import { useState } from 'react';
import FoundFlight from './Components/FoundFlight';
import SearchFlights from './Components/SearchFlights';

function App() {
  const [searchedFlight, setSearchedFlight] = useState('');

  const searchedFlightHandler = (searchedFlightNum) => {
    setSearchedFlight(searchedFlightNum);
  };

  return (
    <div>
      <SearchFlights flightInput={searchedFlightHandler} />
      <FoundFlight userInput={searchedFlight} />
      <FlightList />
    </div>
  );
}

export default App;

下面是我在SearchFlights.js中的代码:

import { useState } from 'react';

const SearchFlights = (props) => {
  const [enteredFlight, setEnteredFlight] = useState('');

  const flightInputHandler = (event) => {
    setEnteredFlight(event.target.value);
    props.flightInput(enteredFlight);
  };

  return (
    <>
      <div className="container">
        <h1>Search Flights</h1>
        <form>
          <label>Enter a flight number</label>
          <input type="text" onChange={flightInputHandler} />
        </form>
      </div>
    </>
  );
};
export default SearchFlights;

下面是我在FoundFlight.js中的代码:

import Card from '../UI/Card';
import { useState } from 'react';
import './FoundFlight.css';

const FoundFlight = (props) => {
  const [filteredFlight, setFilteredFlight] = useState('');
  setFilteredFlight(props.userInput);

  let foundFlightOutput = (
    <Card>
      <p>No flight found yet</p>
    </Card>
  );

  return foundFlightOutput;
};

export default FoundFlight;

在FoundFlight.js中,我使用setFilteredFlight(props. userInput)尝试更新它从App.js接收的值,但在执行此操作时,我收到以下错误:
未捕获的错误:重新呈现太多。React限制呈现次数以防止无限循环
因此,我的问题是,如何在每次更新字符串时将FoundFlight.js中从App.js接收到的字符串值赋给局部变量?

2wnc66cl

2wnc66cl1#

不允许在组件主体中调用setState

const FoundFlight = (props) => {
  const [filteredFlight, setFilteredFlight] = useState('');
  setFilteredFlight(props.userInput);  // <-- no! bad!
  // ...

相反,要使filteredFlightuserInput发生更改时跟踪它,请使用an useEffect hook

const FoundFlight = (props) => {
  const [filteredFlight, setFilteredFlight] = useState(props.userInput);
  useEffect(() => {
    setFilteredFlight(props.userInput);
  }, [props.userInput]);
  // ...

另一方面,如果您不打算允许用户更改该组件中的filteredFlight,那么只需从prop中读取它,就可以完成操作-无需再为需要跟踪的额外状态而烦恼:

const FoundFlight = (props) => {
  const filteredFlight = props.userInput;
  // ...

相关问题