mapStateToProps
返回一个空对象,然后返回正确的对象。除了内部渲染之外,this.props.weights在我的组件中未定义
const mapStateToProps = (state) => {
debugger
return {weights: state.fetchWeights}
}
state = {saveWeight: Array(0), fetchWeights: Array(0)}
const mapStateToProps = (state) => {
debugger
return {weights: state.fetchWeights}
}
state = {saveWeight: Array(0), fetchWeights: Array(1)}
import React, { Component } from 'react';
import { connect } from 'react-redux';
import Weight from '../components/Weight.js';
import '../App.css';
class displayWeights extends Component {
constructor(props) {
super(props);
this.state = {weights: this.props.weights};
}
render() {
return (
<div>
</div>
);
}
}
const mapStateToProps = (state) => {
debugger
return {weights: state.fetchWeights}
}
export default connect(mapStateToProps, {})(displayWeights);
-
import fetch from 'isomorphic-fetch';
export function fetchWeights() {
return function(dispatch){
dispatch({type: 'LOADING'})
var url = 'http://localhost:3001/api/v1/weights.json';
var req = new Request(url);
return fetch(req)
.then(function(response) {
return response.json()
})
.then(function(weights) {
debugger
dispatch({type: 'FETCH_WEIGHTS', payload: weights})
})
}
}
export default (state = [], action) => {
switch (action.type) {
case 'FETCH_WEIGHTS':
debugger
return action.payload
default:
return state;
}
}
import { combineReducers } from 'redux';
import saveWeight from './saveWeightReducer.js';
import fetchWeights from './fetchWeightsReducer.js';
export default combineReducers({
saveWeight,
fetchWeights
});
import React, { Component } from 'react';
import logo from './logo.svg';
import { connect } from 'react-redux';
import {
BrowserRouter as Router,
Route
} from 'react-router-dom';
import DisplayWeights from './containers/DisplayWeights.js'
import NewWeight from './containers/NewWeight.js'
import { fetchWeights } from './actions/fetchWeightsAction.js'
import Chart from './components/Chart.jsx';
import './App.css';
class App extends Component {
componentDidMount() {
this.props.fetchWeights()
}
render() {
return (
<div className="App">
<header className="App-header">
<h1>Welcome to Weight Tracker</h1>
<DisplayWeights />
<NewWeight />
<Chart />
</header>
</div>
);
}
}
export default connect(null, {fetchWeights})(App);
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { Provider } from 'react-redux';
import { store } from './store.js';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
registerServiceWorker();
答案 0 :(得分:0)
您正在触发App组件中对fetchWeights的函数调用,直到DisplayWeights组件的第一个渲染才收到响应,因此在constructor
的{{1}}中未定义响应。另外,如果状态是可直接从道具派生的,则还需要将道具分配给状态,除非您当然希望在本地进行更改,然后在提交时在道具中对其进行更新。