【问题标题】:React: Passing data from between components via RouteReact:通过路由在组件之间传递数据
【发布时间】:2018-01-24 03:59:59
【问题描述】:

我有一个子组件:

import * as React from 'react';
import Select from 'react-select';

import { Link } from 'react-router-dom';
import { Button } from '../controls/Button/Button';
import { ISelectedItem } from '../../interfaces/ISelectedItem';

import * as service from "../../helpers/service";

export interface IProps{
    onClickRender: (selectedItem: ISelectedItem) => void;
}

export interface IState {
    customerData: ISelectedItem[];
    selectedItem: ISelectedItem;
}

export class DropDownSearch extends React.Component<{}, IState>{
    constructor(props: any) {
        super(props);
        this.state = ({
            customerData: [],
            selectedItem: { shortName: '', description: '' }
        });
    }

    componentDidMount() {
        service.fetchJson<ISelectedItem[]>("/api/customers")
            .then((json) =>{
                this.setState({
                    customerData: json
                });
            });
    }

    handleChange = (selectedItem: any) => {
        this.setState({
            selectedItem
        });
    }

    render() {
        const { selectedItem } = this.state;
        const value = selectedItem && selectedItem;

        return (
            <div>
                <Select
                    name="form-field-name"
                    value={this.state.selectedItem}
                    onChange={this.handleChange}
                    options={this.state.customerData}
                    labelKey="shortName"
                />


<Link to={{
 path "/dashboard/" + this.state.selectedItem.shortName,
 state: { detail : this.state.selectedItem }
}}>
                    <Button type="button" className="btn btn-primary" caption="Search" />
                </Link>
            </div>
        );
    }
}

我想将this.state.selectedItem 传递给仪表板组件,它是下面父组件中路由配置的一部分:

import * as React from 'react';

import { Navbar } from './Navbar/Navbar';
import { ShortNameSelector } from './ShortNameSelector/ShortNameSelector';
import { Dashboard } from './Dashboard/Dashboard';
import { BrowserRouter, Route, Switch } from 'react-router-dom';

export class App extends React.Component<{},{}>{
    render(){
        return(
            <BrowserRouter>
                <div className="container">
                    <Navbar />
                    <div className="col-lg-12">
                        <Switch>
                            <Route exact path="/" component={ShortNameSelector} />
                            <Route path="/dashboard" component={Dashboard} />
                        </Switch>
                    </div>
                </div>
            </BrowserRouter>
        );
    }
}

问题是我正在使用路由在子组件中单击按钮时切换组件。如何通过 Routes 将 this.state.selectedItem 对象从子组件传递到 Dashboard 组件(显示在父组件中)?

编辑:

所以我将 state 属性放在 Link 标签内,并在像 this.props.location.state.detail 这样的仪表板组件中引用它,它可以工作。但是现在我想在新页面中打开该链接时将数据保留在该路由/仪表板组件中。我该怎么办?

【问题讨论】:

  • @ShubhamKhatri 根据您提供的链接,我取得了一些进展。但现在我想保留数据。请查看原始帖子以获取更多详细信息。谢谢!

标签: reactjs react-router


【解决方案1】:

你可以这样使用

<Route path="/dashboard/:selectedItem" component={Dashboard} />

因此您可以动态更新 DOM URL 中的选定项目,当您单击它时,您可以使用“仪表板”组件中的“this.props.match.params.id”来访问该值。

【讨论】:

  • selectedItem 是一个对象。在网址中我只想要selectedItem.shortName,但在页面中我还需要selectedItem.description。
  • 那么我认为您可以将这些参数作为查询字符串参数添加到它自己的 URL 中并从“仪表板”组件中读取它们?
  • 就像我说的,我只需要将selectedItem.shortName 作为查询字符串参数放在URL 中,而不是selectedItem.description。那么如何获得selectedItem.description 的值呢?
  • 您可以在更新状态变量时使用该对象(id 和描述)更新会话存储。所以会话存储值可以在任何地方使用。 developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage 或者如果你使用过 Redux,你可以更新 store 并从仪表板组件访问它。
【解决方案2】:

在 React 中通过路由器在组件之间传递对象:我从我的项目中复制了代码片段,可能对你有用。

  1. 我使用 NavLink,它应该将一个对象传递给我的 InfoComponent
<NavLink to={{
            pathname: /menu/${props.data.code},
            search: '',
            state: { selectedMenu: props.data }
          }} color="info" className="btn btn-info btn-success mx-4">Info</NavLink>
  1. 在我的路由器中,然后我收到了路由器中传递的参数,如下所示,添加控制台日志以更清晰
<Route path="/menu/:item" render={(props) => {
              console.log("::::::::: " + JSON.stringify(props.location.state.selectedMenu));
              return (<InfoComponent selectedMenu={props.location.state.selectedMenu} />);
            }} />

【讨论】:

    猜你喜欢
    • 2017-04-26
    • 2016-10-14
    • 2015-03-20
    • 2018-11-11
    • 2019-06-04
    • 2018-02-15
    • 1970-01-01
    • 2016-09-19
    • 1970-01-01
    相关资源
    最近更新 更多