【问题标题】:TypeError: Cannot read property 'state' of undefined React, state passed to other component is undefinedTypeError:无法读取未定义 React 的属性“状态”,传递给其他组件的状态未定义
【发布时间】:2019-10-23 01:07:10
【问题描述】:

当用户输入关键字时,我有一个搜索栏,我通过使用 fetch 对我的后端服务进行 api 调用来获得相关结果。我正在将来自后端的响应存储在我的状态中。下面是 SearchBarComponent 的代码:

import React from 'react';
import Searchbar from 'material-ui-search-bar';
import Redirect from "react-router-dom/es/Redirect";


class SearchBarComponent extends React.Component{
constructor() {
    super();
    this.state = {
        results: [],
        dataFetched: false,
        keyword: 'pre fetch keyword'
    };
    this.fetchData = this.fetchData.bind(this);
};

render() {
    if (this.state.dataFetched) {
        return (
            <Redirect to = {{
                pathname: '/results',
                state: {data: this.state.results}

            }}/>
        )
    }

    return (
        <Searchbar
            onChange = {(value) => this.setState({keyword: value})}
            onRequestSearch={() => {
                this.fetchData(this.state.keyword);
            }
            }
        />
    )
}

fetchData (keyword) {
    let url = 'http://localhost:8080/search?name='+encodeURI(keyword);
    console.log(url);
    fetch(url,{
        mode: 'cors',
        headers: {
            'Access-Control-Allow-Origin':'*'
        }
    })
        .then(response => {
            return response.json()})
        .then(data => {
            this.setState({results: data, dataFetched: !this.state.dataFetched});
        })
}
}

export default SearchBarComponent;

在此之后,我想将我的结果传递给我的 SearchResultsComponet,以便我可以以类似 google 的方式呈现结果。这就是我将传递的状态收集到我的 SearchResultComponent 中的方式:

import React from 'react';

class SearchResultComponent extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            results: this.props.location.state.data.results
        }
    }

    render() {
        return(
            <div>
                <h4>{this.state.results}</h4>
            </div>
    )}

}

export default SearchResultComponent

我在这一行遇到错误results: this.props.location.state.data 我无法弄清楚出了什么问题。任何帮助深表感谢。 我正在通过我的 index.js 文件处理路由,如下所示:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
import ResultsPage from './Pages/ResultsPage'
import {Route, BrowserRouter as Router} from 'react-router-dom';



const routing = (
    <Router>
        <div>
            <Route exact path={'/'} component={App}/>
            <Route path={'/results'} component={SearchResultComponent}/>
        </div>
    </Router>
);

ReactDOM.render(routing, document.getElementById('root'));

【问题讨论】:

  • 我已经编辑了代码,但仍然收到相同的错误 =>“无法读取未定义的属性‘状态’”。实际上,问题在于我将结果组件的状态与搜索组件的传递状态分配在一起
  • 尝试在 SearchResultComponent 的构造函数中添加一个 console.log。然后可以看到this.props.location.state.data.results的哪一部分是未定义的,所以启动this.props.location,然后尝试this.props.location.state,然后this.props.location.state.data,到进一步排除组件树或反应路由器中的错误。并检查来自 fetchData api 调用的数据的形状,它可能与预期不同??

标签: reactjs react-router react-component react-state


【解决方案1】:

您何时/在哪里渲染 SearchResultComponent?

'Cannot read property 'state' of undefined' 表示 this.props.location 未定义。您确定在渲染此组件时您正在传递一个具有值的位置道具吗?

【讨论】:

  • 在“/”上我正在渲染 SearchBarComponent。当用户在搜索栏中输入关键字时,我正在调用 api 以根据该关键字获取结果并将我的应用程序重定向到“/results”以显示获取的结果列表。
  • 是的,当我将状态传递给 SearchResultComponent 时,我会仔细检查,我的状态中确实有更新的值。
【解决方案2】:

您的组件 SearchResultComponent 具有在构造函数中初始化的状态。因此,当在 SearchBarComponent 中第一次调用 render 时,结果设置为空 this.props.location.state.data(顺便说一句,您可以使用 props.location.state.data 代替)。然后在你的结果获取后,SearchResultComponent 的状态没有更新,因为组件已经挂载,所以没有调用构造函数,它在 componentDidUpdate 或 getDerivatedStateFromProps 上。

我看不到您在 SearchBarComponent 中调用 SearchResultComponent 的位置。

但也许你可以这样做:

const SearchResultComponent = props => (
            <div>
                <h4>{props.data}</h4>
            </div>
    )}

}

然后像这样调用你的 SearchResultComponent :

<SearchResultComponent data={this.props.location.data} />

【讨论】:

  • 在获取结果时,我将路径重定向到“/results”,并在那里呈现“SearchResultComponent”。我添加了处理所有路由的 index.js 文件。另外,我尝试了您的解决方案“(顺便说一句,您可以使用 props.location.state.data 代替)”,但这似乎也不起作用。可以做什么??我被卡住了
  • 控制台中的确切错误是什么?或者你有一个我们可以检查你的代码的仓库吗?
猜你喜欢
  • 2019-07-25
  • 1970-01-01
  • 2020-06-17
  • 2021-11-18
  • 2020-08-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多