reactjs - NextJS:在多个页面的多个路由中使用相同的组件
问题描述
在我的 NextJS 应用程序中,我有一个搜索栏组件OrderSearchBar.js
,我想在两个页面中使用它,index.js
但/purchases.js
具有不同的端点。例如,如果我单击index.js
页面上的搜索按钮,它应该将表单内容发布到 /orders/purchases.js
和表单内容应该发布到/purchaseDetails。有什么办法可以做到这一点吗?
OrderSearchBar.js
class OrderSearchBar extends Component{
constructor(props) {
super(props);
this.onChangeInput = this.onChangeInput.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
nature: '',
type: '',
searchBy: '',
startDate: '',
endDate: '',
keyword: ''
}
}
onChangeInput(e) {
this.setState({
[e.target.name]: e.target.value
});
}
onSubmit(e) {
e.preventDefault();
const t = {
nature: this.state.nature,
type: this.state.type,
searchBy: this.state.searchBy,
startDate: this.state.startDate,
endDate: this.state.endDate,
keyword: this.state.keyword
}
axios.post('/search', t)..then(res => console.log(res.data));
/*I can do this for single endpoint.but how do I add multiple endpoints
for use in different pages?*/
this.setState({
nature: '',
type: '',
searchBy: '',
startDate: '',
endDate: '',
keyword: ''
});
}
解决方案
您可以通过获取 window.location 对象的路径名来区分 orderSearchBar.js 中的当前位置。
onSubmit(e) {
e.preventDefault();
const t = {
nature: this.state.nature,
type: this.state.type,
searchBy: this.state.searchBy,
startDate: this.state.startDate,
endDate: this.state.endDate,
keyword: this.state.keyword
}
const pathName = window && window.location.pathname;
const destination = (pathName === '/purchases') ? '/purchaseDetails' : '/orders'
axios.post(destination, t)..then(res => console.log(res.data));
this.setState({
nature: '',
type: '',
searchBy: '',
startDate: '',
endDate: '',
keyword: ''
});
}
推荐阅读
- python - Python 数组和矩阵
- xcode - 在 Xcode 中错误地删除了整个项目的引用
- android - 如何从 sqlite 检索数据到 ListView
- git - 从一个遥控器切换到另一个遥控器后,__git_ps1 只显示提交哈希
- javascript - 合并 2 个数组示例 [a,b,c] [x,y,z] = [a,x,b,y,c,z]
- python - GPflow分类:后验方差的解释
- sql - 如何更新 SQL Server 中的记录,但只能使用参数中的非空值?
- r - 尝试使用 rvest 进行网络抓取时如何修复“UseMethod("xml_find_all") 中的错误”
- python - 版本 Gmsh(版本 >=2)和 Fipy 的问题
- html - AHK 无法加载所有 html