React 函数组件使用 Axios 传递参数到其他页面
要将参数传递到其他页面,可以使用 React Router 库中的 props.history.push 方法来导航到其他页面,并将参数作为查询字符串传递。
首先,您需要在要导航到的页面中定义一个查询字符串参数接收器。您可以使用 React Router 库中的 useLocation 钩子来访问查询字符串参数。
在要接收参数的页面中,您可以使用以下代码:
import { useLocation } from 'react-router-dom';
function MyComponent() {
const location = useLocation();
const myParam = new URLSearchParams(location.search).get('myParam');
return (
<div>
<h1>My Component</h1>
<p>My param is: {myParam}</p>
</div>
);
}
然后,在发送请求的组件中,您可以使用 props.history.push 方法导航到要接收查询字符串参数的页面,并将参数作为查询字符串传递。
例如,您可以使用以下代码:
import axios from 'axios';
import { useHistory } from 'react-router-dom';
function MySendingComponent() {
const history = useHistory();
function handleClick() {
axios.get('/my-api-endpoint', {
params: {
myParam: 'Hello, world!'
}
})
.then(() => {
history.push('/my-receiving-page?myParam=Hello%2C%20world%21');
});
}
return (
<div>
<button onClick={handleClick}>Send Request</button>
</div>
);
}
在此示例中,我们发送一个带有 myParam 参数的 GET 请求,并在请求成功后导航到接收页面,并将 myParam 作为查询字符串传递。注意,我们必须使用 encodeURIComponent 函数对查询字符串参数进行编码,以确保它们可以正确传递。
原文地址: https://www.cveoy.top/t/topic/mLkz 著作权归作者所有。请勿转载和采集!