我有一个非常基本的应用程序,我想读取请求参数值
http://localhost:3000/submission?issueId=1410&score=3
页面:
const Submission = () => {
console.log(this.props.location); // error
return ();
}
export default Submission;
应用
const App = () => (
<Router>
<div className='App'>
<Switch>
<Route path="/" exact component={Dashboard} />
<Route path="/submission" component={Submission} />
<Route path="/test" component={Test} />
</Switch>
</div>
</Router>
);
export default App;
答案 0 :(得分:1)
Did you setup correctly react-router-dom with the HOC in your Submission component ?
Example :
import { withRouter } from 'react-router-dom'
const Submission = ({ history, location }) => (
<button
type='button'
onClick={() => { history.push('/new-location') }}
>
Click Me!
</button>
)
export default withRouter(Submission)
If you already did that you can access the params like that :
const queryString = require('query-string');
const parsed = queryString.parse(props.location.search);
You can also use new URLSearchParams if you want something native and it works for your needs
const params = new URLSearchParams(props.location.search);
const foo = params.get('foo'); // bar
Be careful, i noticed that you have a functional component and you try to access the props with this.props
. It's only for class component.
答案 1 :(得分:0)
When you use a functional component you will need the props
as a parameter of the function declaration. Then the props should be used within this function without this
.
const Submission = (props) => {
console.log(props.location);
return (
<div />
);
};
答案 2 :(得分:0)
The location API provides a search property that allows to get the query parameters of a URL. This can be easily done using the URLSearchParams
object. For example, if the url of your page http://localhost:3000/submission?issueId=1410&score=3
the code will look like:
const searchParams = location.search // location object provided by react-router-dom
const params = new URLSearchParams(searchParams)
const score = params.get('score') // 3
const issueId = params.get('issueId') // 1410