代码之家  ›  专栏  ›  技术社区  ›  Pavindu

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

  •  0
  • Pavindu  · 技术社区  · 6 年前

    在我的nextjs应用程序中,我有一个搜索栏组件 OrderSearchBar.js 我想在两种情况下都使用它 index.js /purchases.js 但端点不同。例如,如果单击 索引文件 第页,它应将表单内容发布到/订单和 购买者 ,表单内容应发布到/purchasedetails。是否有任何方法可以完成此操作?

    File Structure

    订单搜索栏.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: ''         
        });
    }
    
    1 回复  |  直到 6 年前
        1
  •  3
  •   Darryl RN    6 年前

    您可以区分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: ''         
        });
    }