我是redux的新手。我正在尝试启动一个基本的应用程序。我已经看过文件,但我仍然有问题。我收到错误消息NameOfMyAction is not a function.
这只发生在我填写表格并试图通过单击提交将其提交给redux之后。我得到的错误是TypeError: addSodaDrink is not a function
。我将在下面列出我的设置,因为我不知道该怎么说。
//index.js
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import { Provider } from "react-redux";
import {store} from './redux/store';
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById("root")
);
//app.js
import './App.css';
import React from 'react';
import {connect} from 'react-redux';
import { addSodaDrink} from './redux/actionCreators/drinkActions';
class App extends React.Component {
state = {
input: ""
}
handleAddSodaDrink = () => {
const {addSodaDrink} = this.props;
addSodaDrink(this.state.input);
}
handleInput = (e) => {
this.setState(({...this.state, [e.target.name]: e.target.value}))
}
render() {
return (
<div>
{
this.props.sodas.map(soda => {
return (
<p>{soda}</p>
)
})
}
<input name="input" type="text" onChange={this.handleInput} />
<button onClick={this.handleAddSodaDrink}>Add Soda</button>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
sodas: state.sodas
}
}
const mapDispatchToProps = dispatch => {
return {
addSodaDrink: dispatch(addSodaDrink)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
//行动
import { ADD_SODA_DRINK } from "../constants/drinkConstants";
export const addSodaDrink = (drink) => ({type: ADD_SODA_DRINK, payload: drink })
//减速器
import { ADD_SODA_DRINK } from '../constants/drinkConstants';
const defaultState = {
sodas: [],
alcoholic: [],
water: []
}
export const drinkReducer = (state = defaultState, action) => {
switch (action.type) {
case ADD_SODA_DRINK:
const newSodas = state.sodas;
newSodas.push(action.payload);
return newSodas;
default:
console.log(action);
return state;
}
}
//store.js
import { createStore, applyMiddleware } from "redux";
import { drinkReducer } from "./reducers/drinkReducer";
import { composeWithDevTools } from 'redux-devtools-extension'
import thunk from "redux-thunk";
import logger from "redux-logger";
const composedEnhancer = composeWithDevTools(applyMiddleware(logger, thunk))
export const store = createStore(drinkReducer, composedEnhancer)
您需要将addSodaDrink作为一个函数放在mapDispatchToProps中。
const mapDispatchToProps = dispatch => {
return {
addSodaDrink:(input) => dispatch(addSodaDrink(input))
}
}
另一种更简单的方法是将mapDispatchToProps中的操作作为对象。
mapDispatchToProps作为对象
我们有一个处于状态的对象,但您正试图在reducer中为操作ADD_SODA_DRINK
返回一个数组
export const drinkReducer = (state = defaultState, action) => {
switch (action.type) {
case ADD_SODA_DRINK:
const updatedSodas = [ ...state.sodas, action.payload ];
const updatedState = { ...state, sodas: updatedSodas }
return updatedState;
default:
console.log(action);
return state;
}
}