【发布时间】:2020-07-12 06:41:51
【问题描述】:
我有一个 react 子组件的问题,使用 redux 和 react-router。
我通过 this.props.match.params 从 URL 获取一个值,以对 componentDidMount 进行 API 调用。我正在使用 this.props.match.params,因为如果有人直接导航到此特定 URL,我想在我的内容中使用来自 API 的数据。
当我通过单击 a 导航到组件时,组件呈现正常。 API 通过 action 调用,reducer 将数据分发给相关的 prop。
当我通过点击 URL 直接导航到组件时,API 被调用(我可以在 devtools 的 Network 部分看到它被调用),但是数据没有被分派到相关的道具,我没有看到我期望的内容。 我希望通过使用 this.props.match.params 将值传递给 API 调用,我可以直接点击组件并从 API 响应中获取数据,以我想要的方式呈现。
下面是我的组件代码。我怀疑我的 if 语句有问题...但是当我通过单击 React 应用程序中的链接导航到组件时它可以工作。
我错过了什么?
import React from 'react';
import { connect } from 'react-redux';
import { fetchData } from '../../actions';
class Component extends React.Component {
componentDidMount() {
this.props.fetchData(this.props.match.params.id);
}
renderContent() {
if(!this.props.content) {
return (
<article>
<p>Content loading</p>
</article>
)
} else {
return (
<article>
<h2>{this.props.content.title}</h2>
<p>{this.props.content.body}</p>
</article>
)
}
}
render() {
return (
<>
<div className='centered'>
{this.renderContent()}
</div>
</>
)
}
}
const mapStateToProps = (state) => {
return { post: state.content };
}
export default connect(mapStateToProps, { fetchData: fetchData })(Component);
【问题讨论】:
-
你能在
console.log(this.props.match.params.id)和ComponentDidMount中使用相关的reducer 吗?看起来对吗? -
是的,当我点击链接时看起来正确,但是当我直接导航到该页面时,我的控制台中看不到任何登录。
-
我得到的错误是 TypeError: cannot read property of undefined,这表明问题出在组件挂载之前的渲染函数中。这也向我表明 if 语句被忽略......即使 this.props.content 不存在该语句在渲染时被忽略并且 else 语句被返回。我真的对此感到困惑。
-
直接导航时是否看到“内容加载”?
-
你还没有将
this绑定到renderContent
标签: javascript reactjs redux react-router