Eva*_*tes 2 javascript reducers reactjs redux react-redux
我将我的React应用程序与Redux商店连接起来,添加了一个api操作来从我的后端收集数据,包括中间件redux-promise。就像我可以在React Web编辑器中看到我的商店以及Combine Reducer键一样,大多数事情似乎都可以正常工作。当我调用动作时,它会起作用,并且控制台会记录已完成的承诺。但是,我的减速器从未运行过。我以为这是我在主容器上进行分派的问题,但是我已经尝试了所有可以想到的方法-常规dispatch()和bindActionCreators。救命!
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.js';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import promiseMiddleware from 'redux-promise';
import RootReducer from './reducers';
const createStoreWithMiddleware = applyMiddleware(promiseMiddleware)(createStore)
let store = createStore(RootReducer);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root'));`
Run Code Online (Sandbox Code Playgroud)
import { combineReducers } from 'redux';
import ReducerGetPostings from './reducer_get_postings'
const rootReducer = combineReducers({
postingRecords: ReducerGetPostings
})
export default rootReducer;
Run Code Online (Sandbox Code Playgroud)
import { FETCH_POSTINGS } from '../actions/get_postings'
export default function (state = null, action) {
console.log('action received', action)
switch (action.type) {
case FETCH_POSTINGS:
return [ action.payload ]
}
return state;
}
Run Code Online (Sandbox Code Playgroud)
import axios from 'axios';
import { url } from '../api_route';
export const FETCH_POSTINGS = 'FETCH_POSTINGS'
export function fetchpostings() {
const postingRecords = axios.get(`${url}/api/postings`)
console.log('Postings', postingRecords)
return {
type: FETCH_POSTINGS,
payload: postingRecords
};
}
Run Code Online (Sandbox Code Playgroud)
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux'
import { fetchpostings } from '../../actions/get_postings.js'
class Dashboard extends Component {
//....lots of other functionality already built here.
componentDidMount() {
axios.get(`${url}/api/postings`)
.then(res => res.data)
.then(
(postingRecords) => {
this.setState({
postingData: postingRecords,
postingOptions: postingRecords
});
},
(error) => {
this.setState({
error
})
}
)
// primary purpose is to replace the existing api call above with Redux Store and fetchpostings action creator
fetchpostings()
}
}
function mapDispatchToProps(dispatch) {
// return {actions: bindActionCreators({ fetchpostings }, dispatch)}
return {
fetchpostings: () => dispatch(fetchpostings())
}
}
export default connect(null, mapDispatchToProps)(Dashboard);
Run Code Online (Sandbox Code Playgroud)
您不是在调度动作,而是fetchpostings()在调用componentDidMount时,是在调用从导入的方法actions/get_postings.js,而不是将要调度的方法。
试试吧this.props.fetchpostings()。
您也没有将状态绑定到需要做的道具上。
| 归档时间: |
|
| 查看次数: |
612 次 |
| 最近记录: |