2016-12-08 1 views
0

이 문제는 너무 과장되어 있지만 구성 요소가 비동기 적으로 작동하지 않을 수 있습니다.Redux 비동기 요청 문제 (Thunk Middleware)

기본적으로 썽크를 사용하여 로컬 서버에서 JSON을 검색하고 수신하면 감속기로 전달하고 상태를 업데이트하여 구성 요소를 렌더링합니다.

대신 구성 요소는 {} 빈 개체로 앱의 초기 상태를 수신하므로 map을 사용하여 구성 요소를 렌더링 할 때 오류가 발생합니다. 여기

내가 가진 무엇 :

import React from 'react'; 
import ReactDOM from 'react-dom'; 
import { Provider } from 'react-redux'; 
import { createStore, applyMiddleware } from 'redux'; 
import { Router, Route, IndexRoute, browserHistory } from 'react-router'; 
import thunk from 'redux-thunk'; 
import promise from 'redux-promise'; 

import App from './components/app'; 
import VotesContainer from './containers/votes-container'; 
import NewPoll from './containers/newpoll'; 
import VoteTemplate from './components/vote-template'; 
import Login from './components/auth/login'; 
import Signup from './components/auth/signup'; 
import reducers from './reducers/'; 

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; 

const store = createStore(reducers, composeEnhancers(applyMiddleware(thunk))) 

ReactDOM.render(
    <Provider store={store}> 
    <Router history={browserHistory}> 
     <Route path="/" component={App}> 
     <IndexRoute component={VoteTemplate} /> 
     <Route path="allposts" component={VotesContainer} /> 
     <Route path="login" component={Login} /> 
     <Route path="signup" component={Signup} /> 
     <Route path="newpoll" component={NewPoll} /> 
     </Route> 
    </Router> 
    </Provider> 
    , document.querySelector('#project')); 

행동 /하는 index.js를

하는 index.js

import axios from 'axios'; 
const ROOT_URL = 'http://localhost:1234'; 
import { browserHistory } from 'react-router'; 
import { FETCH_VOTES, CAST_VOTE } from './types'; 

export function fetchVotes(){ 
    return function(dispatch){ 
    axios.get(`${ROOT_URL}/newpost`) 
     .then(response => { 
     console.log('Dispatch!!') 
     dispatch({ 
      type: FETCH_VOTES, 
      payload: response.data 
     }) 
     }) 
    } 
} 

용기

import React, { Component } from 'react'; 
import { connect } from 'react-redux'; 
import * as actions from '../actions' 

class VotesContainer extends Component { 
    componentDidMount(){ 
    this.props.fetchVotes() 
    } 
    renderCards(){ 
    return(
     <div className="col s12 m6 l4"> 
     <div className="card blue-grey darken-1"> 
      <div className="card-content white-text"> 
      <span className="card-title">Vote App Title #1</span> 
      <p className="description">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p> 
      </div> 
      <div className="card-action"> 
      <a href="#">Results</a> 
      <a href="#">Date Created</a> 
      </div> 
     </div> 
     </div> 
    ) 
    } 
    render(){ 
    console.log(this.props.voteData) 
    return(
     <main className="votes-container container"> 
     <div className="row"> 
      {this.props.voteData.map(this.props.voteData.vote)} <<======= gives error since it is null first before dispatch 
     </div> 
     </main> 
    ) 
    } 
} 

function mapStateToProps(state){ 
    return {voteData: state.voteData}; 
} 

export default connect(mapStateToProps, actions)(VotesContainer) 
+0

개체에서지도를 사용할 수 없으며 개체 키로 사용하려고합니까? – Kafo

+0

죄송합니다. 오타입니다.'this.props.voteData.vote' 여야합니다. – Alejandro

+1

배열을 보호 할 수 있습니다. '(this.props.voteData.vote || []). map (this.renderCards)'를하면 원하는 것을 할 수 있습니다. 빈 객체 인 초기 상태부터 시작하여 서버에서 다른 초기 상태로 시작하지 않으려는 경우 파견 할 때 채워집니다. – Kafo

답변

1

구성 요소에서 기대하는대로 상점의 초기 상태를 설정해야합니다.
만약 당신이 그것을하지 않으면 모든 데이터가 먼저 거기에있을 것이라고 기대해서는 안됩니다 render. 데이터를 가져온 후에 만 ​​데이터가 제공 될 때까지 구성 요소에 몇 가지 안전 검사를 추가 할 수 있습니다.

+0

아하이 봐요. 나는'componentDidMount'가 불려질 때 비동기 적으로 가져 오는 것이고, 데이터를 가져올 때까지 컴포넌트를 렌더링하지 않을 것이라고 생각했을 것입니다. 예, 안전 검사를 추가하면 완벽하게 작동합니다. – Alejandro

+1

@Alejandro : 아니요, 데이터를 기다리는 동안 데이터가 비동기 프로세스가 될 때까지 기다리는 것으로 렌더링이 호출됩니다. 데이터를 받으면 상태가 업데이트 됨 -> 렌더링이 다시 호출 됨 –

관련 문제