出现此错误(尝试学习redux / react)时,不确定错误的来源...
我确实尝试在这里和Google上找到答案,但是我尝试的所有操作均未解决问题。
我仍在学习,因此,如果您可以提供全面的解决方案,将不胜感激:)
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux'
import { store } from './redux/store'
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);
* App.js
import React, { Component } from 'react';
import { connect } from 'react-redux'
import { toggle } from "./redux/action";
import './App.css';
class App extends Component {
render() {
return (
<div>
{this.props.toggle ? <h1>Hi</h1> : <h1>Bye</h1>}
<button onClick={this.props.onToggle}>Click Me</button>
</div>
)
}
}
const mapStateToProps = state => {
return {
toggle: state.isCorrect
};
}
const mapsDispatchToProps = dispatch => {
return {
onToggle: (bool) => dispatch(toggle(bool))
};
}
export default connect(mapStateToProps, mapsDispatchToProps)(App)
store.js
import {createStore, applyMiddleware, compose} from 'redux'
import thunk from 'react-thunk'
const INITIAL_STATE = {
isCorrect: false
}
const reducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case 'IS_CORRECT':
return {
...state,
isCorrect: state.isCorrect = !state.isCorrect
}
}
return state;
};
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
export const store = createStore(
reducer,
composeEnhancers(applyMiddleware(thunk))
);
action.js
export const toggle = (bool) => {
return {
type: "IS_CORRECT",
state: bool
};
}
错误
index.js:37 Uncaught TypeError: Cannot call a class as a function
at _classCallCheck (index.js:37)
at ReactThunk[Component] (index.js:80)
at redux.js:644
at <anonymous>:1:28399
at createStore (redux.js:79)
at Module../src/redux/store.js (store.js:21)
at __webpack_require__ (bootstrap:785)
at fn (bootstrap:150)
at Module../src/index.js (index.css?e32c:37)
at __webpack_require__ (bootstrap:785)
at fn (bootstrap:150)
at Object.0 (serviceWorker.js:135)
at __webpack_require__ (bootstrap:785)
at checkDeferredModules (bootstrap:45)
at Array.webpackJsonpCallback [as push] (bootstrap:32)
at main.chunk.js:1
答案 0 :(得分:1)
错误在store.js文件中,您错误地导入了thunk。
import thunk from 'redux-thunk'
应该是“ redux-thunk”,而不是像上面那样反应-thunk。
答案 1 :(得分:0)
class App extends Component {
render() {
return (
<div>
{this.props.toggle ? <h1>Hi</h1> : <h1>Bye</h1>}
<button onClick={() => this.props.onToggle(!this.props.toggle)}>Click Me</button>
</div>
)
}
}
不确定这是否可以解决问题。提供完整的错误堆栈会很有帮助。并提供./redux/actions.js文件