【发布时间】:2018-04-20 01:26:36
【问题描述】:
我开始反应和减少,我已经使用 combineReducers 并得到 p>
未捕获的类型错误:无法将未定义或 null 转换为对象。
没有 combineReducer 它工作正常。下面是我的 Reducer 的 sn-p。
reducers\article.js:
import { ADD_ARTICLE } from "../actiontypes/action-types";
const initialState = {
articles: []
};
const articleReducer = (state = initialState, action) => {
switch (action.type){
case ADD_ARTICLE:
return {...state, articles: [...state.articles, action.payload] };
default:
return state;
}
};
export default articleReducer;
reducers\index.js
import { combineReducers } from "redux";
import articleReducer from "./article";
export default combineReducers({
articles : articleReducer
});
actions\index.js
import {ADD_ARTICLE} from "../actiontypes/action-types";
export const addArticle = article => ({type: ADD_ARTICLE, payload: article});
store/index.js
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from '../reducers';
const initialArticlesState = {
articles: [{"title":"some title", "id":"04503"}]
};
const middleware = [thunk];
const store = createStore(
rootReducer,
initialArticlesState,
compose(
applyMiddleware(...middleware),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
)
);
export default store;
components\form.js
import React, { Component } from "react";
import { connect } from "react-redux";
import uuidv1 from "uuid";
import { addArticle } from "../js/actions/index";
class ConnectedForm extends Component {
constructor(){
super();
this.state = {
title: ""
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event.preventDefault();
const { title } = this.state;
const id = uuidv1();
console.log("submit",{ title, id });
this.props.addArticle();
this.setState({ title: "" });
}
handleChange(event) {
this.setState({ [event.target.id]: event.target.value});
}
render() {
const { title } = this.state;
return (
<form onSubmit={this.handleSubmit}>
<div className="form-group">
<label htmlFor="title">Title</label>
<input
type="text"
className="form-control"
id="title"
value={title}
onChange={this.handleChange}
/>
</div>
<button type="submit" className="btn btn-success btn-lg">
SAVE
</button>
</form>
);
}
}
const mapDispatchToProps = dispatch => {
return {
addArticle: article => dispatch(addArticle(article))
};
};
const Form = connect(null, mapDispatchToProps)(ConnectedForm);
export default Form;
【问题讨论】:
-
您有一些奇怪的字符,例如
“、‘或三个点。有没有副本/过去的问题? -
那些是三个点 (...) 扩展运算符,我认为在将其粘贴到此处时它已更改。我已经编辑了帖子。
-
我知道他们是传播运营商,但不是标准运营商 :) 创建商店对我来说没有问题:codesandbox.io/s/5zk94ylnxn 当然我没有尝试过任何操作,但商店方面还可以。你是如何行动的,你如何应用它?如果可能,请发布您的整个代码。
-
能否请您在创建商店的位置发布代码?
-
更新帖子