簡體   English   中英

使用react-router時,是否存在將道具從有狀態組件傳遞到無狀態組件的另一種方法

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

我有一個包含四個路線和一個搜索組件的應用程序。 從那里,我想將信息數組從api傳遞到無狀態結果表。 我知道狀態會在搜索組件中更新,但由於某種原因不會傳遞到下一個組件。

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

這就是結果調用

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

路由是在app.js文件中設置的,當我運行搜索功能時,會告訴我props.results未定義。 這是結果代碼:

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