我应该如何将数据从 react app.js 传递到 profile.js 并在 url 中设置 id?

How should I pass data from react app.js to profile.js and set id in url?

编辑了 post!!!

id 来自登录请求,在 handleChangeId 的 else 分支!它得到了正确的ID!我试着顶上去!

export function Login({handleChangeId}) {

const login = () => {

//node port egyezés szükséges
Axios.post('http://localhost:3001/login', {

    LoginUsername: usernameLog,
    LoginPassword: passwordLog,
}).then((response) => { 

    if (response.data.message) {
        setLoginCorrect(response.data.message)
    }

    else {
        handleChangeId(response.data[0].id);
        navigate("/App");
    }
});
};
}

比 App.js 我尝试从登录路线获取 ID,并通过配置文件路线推送

let id = null;

function changeID(newId) {
  id= newId;
}

ReactDOM.render(
  <BrowserRouter>
    <Routes>
      <Route exact path="/" element={<Login handleChangeId={changeID} />}
      <Route exact path="/profile" element={<Profile id={id} />} />
    </Routes>
  </BrowserRouter>,
  document.getElementById('root')
); />

在Profile.js,我也尝试通过这种方式获取 id,但是我尝试过的所有方法的值都=null!这就是我要找的 - 当用户点击菜单栏上的个人资料时,如何读取和设置 ID 并获取他们的个人数据!

export function Profile({ id }) {

    const [customers, setCustomers] = useState([]);

    useEffect(() => {
        Axios.get(`http://localhost:3001/profile?userId=${id}`)
            .then((response) => {
                if (response) {

                    setCustomers(response.data);
                }
                else {
                    alert("Data currently unavailable!")
                }
            });
    }, []);
}

问题

let id = null;

function changeID(newId) {
  id= newId;
}

不起作用,因为 id 在每个渲染周期都被声明为空值,并且简单地改变它不会触发组件重新渲染,并将更新后的值传递给 Profile组件。

解决方案

使 id 成为组件状态的一部分,因此更新它会触发重新渲染,更新后的值在范围内关闭。

示例:

const [id, setId] = React.useState(null);

...

const changeID = (newId) => {
  setId(newId);
}

...

<Routes>
  <Route path="/" element={<Login handleChangeId={changeID} />}
  <Route
    path="/profile"
    element={<Profile id={id} />} // <-- updated id state value passed here
  />
</Routes>