简体   繁体   English

使用react-router时,是否存在将道具从有状态组件传递到无状态组件的另一种方法

[英]When using react-router, is there a different way to pass props from a stateful component to a stateless one

I have an app with four routes, and a search component. 我有一个包含四个路线和一个搜索组件的应用程序。 from there I want to pass an array of info from an api to a stateless results table. 从那里,我想将信息数组从api传递到无状态结果表。 I know that the state gets updated in the search component, but for some reason won't pass on the the next component. 我知道状态会在搜索组件中更新,但由于某种原因不会传递到下一个组件。

class Search extends Component {
    constructor(props) {
        super(props)
        this.state = {
                    driverLicense: null,
                    birthMonth: null,
                    birthDay: null,
                    birthYear: null,
                    showResults: false,
                    results: []
                }
    }

    componentDidMount() {
        fetch('/api/violators')
            .then(res => res.json())
            .then(results => this.setState({ results }));

then this is the call to results component 这就是结果调用

<Results
 data={this.state.results} />

the routes are set up in the app.js file, when I run the search function tells me props.results in undefined. 路由是在app.js文件中设置的,当我运行搜索功能时,会告诉我props.results未定义。 here is the results code: 这是结果代码:

import React from 'react';

import { Table } from 'semantic-ui-react';

const Results = (props) => {

        return(
            <div>
                <Table celled>
                    <Table.Header>
                        <Table.Row>
                            <Table.HeaderCell>First Name</Table.HeaderCell>
                            <Table.HeaderCell>Last Name</Table.HeaderCell>
                        </Table.Row>
                    </Table.Header>
                    <Table.Body>
                        <Table.Row>
                            {props.results.map(props => 
                                <Table.Cell key={props.id}>{props.firstName}</Table.Cell>
                            )}
                            <Table.Cell>test</Table.Cell>
                        </Table.Row>
                    </Table.Body>
                </Table>
            </div>
        )
}

export default Results;

您将结果作为data prop传递,并且需要像props.data一样访问它,而不是props.results

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM