问题描述
https://master.deeiswmgeowge.amplifyapp.com/?site=gfg&subject=react
那么,this.props
为空。
以下为原文。
import React,{ Component } from "react";
// Importing Module
import queryString from 'query-string'
class App extends Component {
state = {
site: 'unkNown',subject: 'i dont kNow'
}
handleQueryString = () => {
// Parsing the query string
// Using parse method
console.log(`this.props`,this.props)
let queries = queryString.parse(this.props.location.search)
console.log(queries)
this.setState(queries)
}
render() {
return (
<div style={{ margin: 200 }}>
<p> WebSite: {this.state.site} </p>
<p> Subject: {this.state.subject} </p>
<button
onClick={this.handleQueryString}
className='btn btn-primary'>
click me
</button>
</div>
);
}
}
export default App;
"dependencies": {
"@testing-library/jest-dom": "^5.11.4","@testing-library/react": "^11.1.0","@testing-library/user-event": "^12.1.10","query-string": "^6.14.0","react": "^17.0.1","react-dom": "^17.0.1","react-scripts": "4.0.2","web-vitals": "^1.0.1"
},
这是错误图像。
解决方法
您没有使用 react router ,因此道具中没有位置参数:
所以你有两个解决方案,
-
1 是否添加
react-router-dom
并使用 router 包装您的应用,(或与路由器挂钩使用,如export default withRouter(App)
) -
2 或直接访问
获取参数window.location.search
并使用 URLSearchParams
举例:
const urlParams = new URLSearchParams(window.location.search);
const site = urlParams.get('site');
const subject = urlParams.get('subject');
,
需要传递道具之类的
onClick={()=> this.handleQueryString(this.props)}
收到喜欢
handleQueryString(arg) {
....
}