gpt4 book ai didi

reactjs - react -Redux 错误 : Element type is invalid after connect

转载 作者:行者123 更新时间:2023-12-05 06:57:42 25 4
gpt4 key购买 nike

我正在尝试学习 React - Redux。我创建了一个如下所示的考试组件:

class ExamHome extends React.Component {

constructor(props) {
super(props)
}

render() {
return (
<TabPane>
<Exam />
</TabPane>
)
}
}

export default ExamHome;

我创建了一个 Exam React 组件,如下所示:

class Exam extends React.Component {

constructor(props) {
super(props)
}

render() {
return (
"hello"
)
}
}

const mapStateToProps = state => {
return {
examUrl: state.examApp.examUrl
}
};

export default connect(mapStateToProps, {
showExam
})(Exam);

这是我的 reducer :

let initialState = {
examUrl: null
}

const exam = (state = initialState, action) => {
switch (action.type) {
case "SHOW_EXAM":
return { ...state, examUrl: action.examToken }

default:
return state
}
};

export default exam

这是我的操作:

export const showExam = t => {
return dispatch => dispatch({
type : "SHOW_EXAM", examToken : t
})
}

如果我删除 connect 它工作正常如果我添加 connect 我得到以下错误:

Error: Element type is invalid: expected a string (for built-incomponents) or a class/function (for composite components) but got:object.

Check the render method of ExamHome.

我尝试了在 Stackoverflow 中找到的所有可能的解决方案,但没有一个有效。感谢您的帮助。

编辑:

这是rootReducer.js

import { combineReducers } from "redux"
import { connectRouter } from 'connected-react-router'
import customizer from "./customizer/"
import auth from "./auth/"
import navbar from "./navbar/Index"
import exam from "./exam/exam"

const rootReducer = (history) => combineReducers({
customizer: customizer,
auth: auth,
navbar: navbar,
exam: exam,
router: connectRouter(history)
})

export default rootReducer

最佳答案

你只需要定义你的 dispatch 和 return to connect 函数并使用 componentDidMount 运行它:

import * as Actions from "path of showExam, Actions file only";

class Exam extends React.Component {

componentDidMount() {
props.onShowExam("any value you want in default");
}

constructor(props) {
super(props)
....
}

const mapStateToProps = state => {
return {
examUrl: state.examApp.examUrl
}
};

const mapDispatchToProps = dispatch => {
return {
onShowExam: (val) => dispatch(Actions.showExam(val))
}
};

export default connect(mapStateToProps, mapDispatchToProps)(Exam);

关于reactjs - react -Redux 错误 : Element type is invalid after connect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64864424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com