[英]React component will not receive props passed to it. When rendered with a logical operator
[英]Props not rendered when navigating to component directly - React Redux
我的反應子組件有問題,使用 redux 和 react-router。
我通過 this.props.match.params 從 URL 獲取一個值,以便對 componentDidMount 進行 API 調用。 我正在使用 this.props.match.params ,因為如果有人直接導航到這個特定的 URL,我想在我的內容中使用來自 API 的數據。
當我通過單擊 a 導航到該組件時,該組件呈現良好。 API 通過操作調用,reducer 將數據分派到相關的 prop。
當我通過點擊 URL 直接導航到組件時,API 被調用(我可以在 devtools 的 Network 部分看到它被調用),但是數據沒有被分派到相關的 prop 並且我看不到我的內容預計。 我希望通過使用 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);
嘗試將renderContent
更新為:
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>
)
}
}
它看起來像你忘了綁定this
到renderContent
我解決了問題,非常感謝您的幫助!
結果發現 API 請求返回的是一個數組,而我的操作是將這個數組分派到 props.content。 這個特定的 API 調用將始終返回一個只有一個值的數組(根據文檔,它被設計為返回單個條目……但由於某種原因,它以數組形式返回!)。 我期待一個對象,所以我是這樣對待它的。 我在我的減速器中將數組轉換為一個對象,現在它的行為正常。
所以總的來說,我的數據結構有問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.