【发布时间】:2018-05-15 09:18:10
【问题描述】:
我创建商店如下:
import { createStore, applyMiddleware } from 'redux';
import { logger } from 'redux-logger';
import rootReducer from './reducers/rootReducer';
import { compose } from 'redux';
const InitialState = {
texts: [],
item: {}
}
const store = createStore(
rootReducer,
InitialState,
applyMiddleware(logger),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
)
export default store;
这是我的 userActions 文件:
import { ADD_TEXT } from './types';
export const addText = () => (dispatch) => {
const obj = [
{
id: 0,
type: 'Apacze',
text: 'przykaldowyTeksciorNa start'
},
{
id: 1,
type: 'Apacze',
text: 'przykladowyTekst2'
}
]
dispatch({
type: ADD_TEXT,
payload: obj
})
}
这是我的 userReducer 如下:
import { ADD_TEXT, LISTED_USER } from '../actions/types';
const InitialState = {
texts: [],
item: {}
}
export const userReducer = (state=InitialState, action) => {
switch(action.type) {
case ADD_TEXT: {
return {
...state,
texts: action.payload
}
}
case LISTED_USER: {
return {
...state,
items: action.payload
}
}
default: {
return state
}
}
}
这是我的 React 组件,我在其中使用了我的 Redux 操作:
import React, { Component } from 'react';
import ApaczeView from '../view/ApaczeView';
import { addText } from '../redux/actions/userActions';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
class Apacze extends Component {
constructor(props) {
super(props);
this.state = {
text: 'Dokończ zaczętą historie, to od ciebie zależy jak potoczą się dalsze losy bohaterów.'
}
this.changeTekst = this.changeTekst.bind(this);
this.addText = this.addText.bind(this);
}
changeTekst(e) {
this.setState({
[e.target.getAttribute('name')]: [e.target.innerHTML]
})
}
addText(e) {
this.props.dispatch(addText());
}
render() {
return(
<ApaczeView text={this.state.text} changeTekst={this.changeTekst} addText={this.addText} />
)
}
}
Apacze.PropTypes = {
dispatch: PropTypes.func.isRequired,
texts: PropTypes.array.isRequired
}
const mapStateToProps = (state) => ({
texts: state.users.texts
})
export default connect(mapStateToProps ) (Apacze);
我几乎尝试了所有方法,包括来自 stackoverflow 的类似解决问题。不幸的是,在我的情况下,没有一个类似的解决问题不起作用。
【问题讨论】:
-
你必须实现
redux-thunk中间件才能使用dispatch -
谢谢,工作。我仍然无法相信,简单的解决方法解决了我的问题。再次感谢你非常匹配:)
标签: reactjs react-redux jsx react-proptypes