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

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

本文介绍了NextJS:在多个页面的多个路由中使用相同的组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my NextJS app, I have a search bar component OrderSearchBar.js and I want to use it in both index.js and /purchases.js pages but with different endpoints.For example,if I click search button on the index.js page,it should post form content to /orders and on the /purchases.js, form content should post to /purchaseDetails.Is there any way to accomplish this?

OrderSearchBar.js

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 对象的路径名.

You can differentiate the current location in your orderSearchBar.jsby getting the pathname of window.location object.

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

这篇关于NextJS:在多个页面的多个路由中使用相同的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 00:38