我正在用Redux和React製作一個非常簡單的ToDo列表。嘗試添加待辦事項時,出現「Uncaught ReferenceError:type is not defined」。我嘗試了幾件事,這裏是我現在的代碼。任何想法我做錯了什麼?謝謝!在React/Redux中獲取「Uncaught ReferenceError:type is not defined」錯誤?
這裏是我的容器:
import React, {Component} from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { addTodo } from '../actions/index';
class Todos extends Component {
constructor(props) {
super(props);
this.state = {text: ''};
}
addTodo(e) {
e.preventDefault();
this.props.addTodo(this.state.text);
this.setState({
text: ''
});
}
updateValue(e) {
this.setState({text: e.target.value})
}
render() {
return (
<div>
<form onSubmit={(e) => this.addTodo(e)}>
<input
placeholder="Add Todo"
value={this.state.text}
onChange={(e) => {
this.updateValue(e)
}}
/>
<button type="submit">Add Todo</button>
</form>
<ul>
{ this.props.todo.map((item) => {
return <li key={item.id}>{ item.message }</li>
})}
</ul>
</div>
);
}
}
function mapStateToProps({ todo }) {
return { todo }
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({addTodo}, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(Todos);
這裏是減速機:
import { ADD_TODO } from '../actions/types';
export default function(state=[], action) {
switch(action.type) {
case ADD_TODO:
return [ action.payload.message, ...state ]
}
return state;
}
而且../reducers/index.js
import { combineReducers } from 'redux';
import TodosReducer from './reducer_addTodo';
const rootReducer = combineReducers({
todo: TodosReducer
});
export default rootReducer;
和動作:
import { ADD_TODO } from './types';
const uid =() => Math.random().toString(34).slice(2);
export function addTodo(message) {
const action = {
id: uid(),
message: message
};
return(
type: ADD_TODO,
payload: action
)
}
當嘗試添加待辦事項,我得到以下錯誤:
Uncaught ReferenceError: type is not defined
at addTodo (bundle.js:21950)
at Object.addTodo (bundle.js:21166)
at Todos.addTodo (bundle.js:23541)
at onSubmit (bundle.js:23562)
at Object.ReactErrorUtils.invokeGuardedCallback (bundle.js:4532)
at executeDispatch (bundle.js:4332)
at Object.executeDispatchesInOrder (bundle.js:4355)
at executeDispatchesAndRelease (bundle.js:3785)
at executeDispatchesAndReleaseTopLevel (bundle.js:3796)
at Array.forEach (<anonymous>)
編輯:
這裏是types.js文件:
export const ADD_TODO = 'ADD_TODO';
更換括號我現在添加了types.js文件,只有有ADD_TODO。 – userden
你有沒有試過用我的答案解決你的問題? –