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

时间:2019-01-15 05:49:33

标签: reactjs routing next.js

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

File Structure

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

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

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

相反,我建议您将prop传递到组件,例如:

<component :type="'isPurchaseDetails'">

或用于购买

<component :type="'isPurchases'">