[英]Problem connecting component to Redux store
我無法將我的 HomePage(App 組件的子組件)組件連接到 Redux 商店。 在 componentDidMount => 我嘗試在我的文件底部調用 connect 並作為第二個參數傳遞 function 我從我的操作創建器文件中導入,該文件將獲取到我的后端以在 React 存儲中設置數據。 但是,我收到錯誤消息說定義和導入的 function “不是函數”。 我似乎無法通過我的 componentDidMount 調用。 我也無法從此組件訪問商店。
我已經嘗試直接從我的組件調度一個動作。 我在每個被調用的 function 中都使用了調試器(盡管我沒有通過 ComponentDidMount。我還嘗試使用 withRouter 將我的連接包裝在里面。
*** Action Creator File ***
export const getSectors = ticker => {
return dispatch => {
fetch("http://localhost:3000/quote/sectors")
.then(response => response.json())
.then(data => dispatch({ type: "GET_SECTORS", data }));
};
};
******************************************************************
*** HomePage Component File ***
import React from "react";
import styled from "styled-components";
import { connect } from "react-redux";
import { getSectors } from "../redux/actions";
export class HomePage extends React.Component {
componentDidMount() {
// debugger;
this.props.getSectors("test");
}
render() {
debugger;
return (
<HomePageWrapper>
<div className="main">
<div className="leftSide">
<div> Mini Prof Card</div>
<div>Leaderboard Card</div>
<div>Trending news #</div>
</div>
<div className="feed"> two </div>
<div className="rightSide"> three </div>
</div>
{/* <div className="footer">footer</div> */}
</HomePageWrapper>
);
}
}
const mapStateToProps = state => {
return { state };
};
export default connect(
mapStateToProps,
{ getSectors }
)(HomePage);
*** Client Side Error Message
TypeError: this.props.getSectors is not a function
HomePage.componentDidMount
src/containers/HomePage.js:80
77 | export class HomePage extends React.Component {
78 | componentDidMount() {
79 | // debugger;
> 80 | this.props.getSectors("test");
81 | }
82 |
83 | render() {
23 stack frames were collapsed.
(anonymous function)
src/redux/actions.js:43
40 | })
41 | .then(r => r.json())
42 | .then(data => {
> 43 | dispatch({ type: "UPDATE_USER", data });
| ^ 44 | });
45 | } else {
46 | return { error: "not found" };
I was expecting to hit my debugger in my action creator file but never got there.```
您正在導出原始組件和連接的組件。
您可能正在導入未連接的組件,例如import { HomePage } from "./this-file"
但您要使用的是默認導出。
import HomePage from "./this-file"
將導入默認導出,即用connect
包裝的組件。
如果不需要避免此問題,我建議根本不要導出HomePage
組件。 或者將其命名為HomePageBase
或UnconnectedHomePage
,以便一眼就能看出它不是正確的組件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.