首页 > 解决方案 > 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: ''         
    });
}

标签: reactjsroutingnext.js

解决方案


您可以通过获取 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: ''         
    });
}


推荐阅读