Реагировать на изменение URL, но не на компонент - PullRequest
0 голосов
/ 12 марта 2019

Я нажимаю на ссылку, URL-адрес изменяется, но компонент остается.

вот файл Router.js:

import React, {Component} from 'react';
import Navbar from "./Navbar";
import {Route, Switch} from "react-router-dom";
import ProductsList from "./ProductsList";
import ProductDetails from "./ProductDetails";
import Dashboard from "./Dashboard";

class Router extends Component {
    render() {
        return (
            <div>
                <Navbar/>
                <Switch>
                    <Route exact path="/" component={Dashboard}/>
                    <Route exact path="/products" component={ProductsList}/>
                    <Route path="/productdetails" component={ProductDetails}/>
                </Switch>
            </div>
        );
    }
}

export default Router;

вот файл productslist.js, где я нажимаю на ссылку:

import React from 'react';
import {Table, Input, Button, Icon, Divider} from 'antd';
import Highlighter from 'react-highlight-words';
import {getProducts} from "../actions/productsActions";
import {connect} from 'react-redux'
import {Link} from "react-router-dom";

class ProductsList extends React.Component {
    state = {
        searchText: '',
    };

    componentDidMount() {
        this.props.getProducts();
    }

    getColumnSearchProps = (dataIndex) => ({
        filterDropdown: ({
                             setSelectedKeys, selectedKeys, confirm, clearFilters,
                         }) => (
            <div style={{ padding: 8 }}>
                <Input
                    ref={node => { this.searchInput = node; }}
                    placeholder={`Search ${dataIndex}`}
                    value={selectedKeys[0]}
                    onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                    onPressEnter={() => this.handleSearch(selectedKeys, confirm)}
                    style={{ width: 188, marginBottom: 8, display: 'block' }}
                />
                <Button
                    type="primary"
                    onClick={() => this.handleSearch(selectedKeys, confirm)}
                    icon="search"
                    size="small"
                    style={{ width: 90, marginRight: 8 }}
                >
                    Search
                </Button>
                <Button
                    onClick={() => this.handleReset(clearFilters)}
                    size="small"
                    style={{ width: 90 }}
                >
                    Reset
                </Button>
            </div>
        ),
        filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#1890ff' : undefined }} />,
        onFilter: (value, record) => record[dataIndex].toString().toLowerCase().includes(value.toLowerCase()),
        onFilterDropdownVisibleChange: (visible) => {
            if (visible) {
                setTimeout(() => this.searchInput.select());
            }
        },
        render: (text) => (
            <Highlighter
                highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
                searchWords={[this.state.searchText]}
                autoEscape
                textToHighlight={text.toString()}
            />
        ),
    })

    handleSearch = (selectedKeys, confirm) => {
        confirm();
        this.setState({ searchText: selectedKeys[0] });
    }

    handleReset = (clearFilters) => {
        clearFilters();
        this.setState({ searchText: '' });
    }

    render() {
        const data = this.props.productsList.map(product => {
                return {
                    key: product.id,
                    product_name: product.product_name,
                    id: product.id,
                    product_price: product.product_price,
                    product_gender: product.product_gender,
                    product_category: product.product_category,
                    product_campaign: product.product_campaign,
                    product_description: product.product_description


                }
            });
        const columns = [{
            title: 'Name',
            dataIndex: 'product_name',
            key: 'product_name',
            width: '20%',
            ...this.getColumnSearchProps('product_name')
        }, {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
            width: '10%',
            ...this.getColumnSearchProps('id')
        }, {
            title: 'Price',
            dataIndex: 'product_price',
            key: 'product_price',
            width: '10%',
            ...this.getColumnSearchProps('product_price'),
        }, {
            title: 'Gender',
            dataIndex: 'product_gender',
            key: 'product_gender',
            width: '10%',
            ...this.getColumnSearchProps('product_gender'),
        }, {
            title: 'Category',
            dataIndex: 'product_category',
            key: 'product_category',
            width: '10%',
            ...this.getColumnSearchProps('product_category'),
        }, {
            title: 'Campaign',
            dataIndex: 'product_campaign',
            key: 'product_campaign',
            width: '10%',
            ...this.getColumnSearchProps('product_campaign'),
        }, {
            title: 'Description',
            dataIndex: 'product_description',
            key: 'product_description',
            ...this.getColumnSearchProps('product_description'),
        }, {
            title: 'Action',
            key: 'action',
            render: (text, record) => (
                <span>
                <Link to={`/productdetails`}>Edit</Link>
                <Divider type="vertical" />
                <a href="javascript:">Delete</a>
                </span>
            ),
        }];
        return <Table columns={columns} dataSource={data} pagination={{ pageSize: 16 }} />;
    }
}

const mapStateToProps = state => {
    return {
        productsList: state.productsReducer.products
    }
};

export default connect(mapStateToProps, {getProducts})(ProductsList);

Таким образом, в productslist.js я нажимаю кнопку «Изменить», и URL-адрес изменяется на / productdetails, но я остаюсь в том же компоненте productlist, честно говоря, маршрутизация в React тупо грязная, почему они не реализуют более прямую маршрутизацию ....

Любая помощь осуществляется

1 Ответ

0 голосов
/ 12 марта 2019

Вы забыли использовать в своем коде

import React, {Component} from 'react';
import Navbar from "./Navbar";
import {Route, Switch, BrowserRouter} from "react-router-dom"; // <- you forgot to import <BrowserRouter>
import ProductsList from "./ProductsList";
import ProductDetails from "./ProductDetails";
import Dashboard from "./Dashboard";

class Router extends Component {
    render() {
        return (
            <div>
                <Navbar/>
                <BrowserRouter> {/* You need to wrap your Routes in BrowserRouter */}
                  <Switch>
                      <Route exact path="/" component={Dashboard}/>
                      <Route exact path="/products" component={ProductsList}/>
                      <Route path="/productdetails" component={ProductDetails}/>
                  </Switch>
                </BrowserRouter>
            </div>
        );
    }
}

export default Router;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...