NextJS:在多个页面的多个路由中使用相同的组件

NextJS: Use same component in multiple routes for multiple pages

在我的 NextJS 应用程序中,我有一个搜索栏组件 OrderSearchBar.js,我想在 index.js/purchases.js 页面中使用它,但使用不同的 endpoints.For 示例,如果我点击 index.js 页面上的搜索按钮,它应该 post 表单内容到 /orders 而在 /purchases.js 上,表单内容应该 post 到 /purchaseDetails.Is 有什么办法可以做到吗?

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: ''         
    });
}

您可以在 orderSearchBar.js 中区分当前位置 通过获取 window.location 对象的路径名。

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: ''         
    });
}

虽然您可以使用 window 属性,但如果您使用 Nuxt.js 或其他服务器端渲染,这可能不起作用,因为 window 对象不是目前。

相反,我建议您将一个 prop 传递给您的组件,例如:

<component :type="'isPurchaseDetails'">

或购买

<component :type="'isPurchases'">