2017-12-20 19 views
0

"ReduxPromise"を使わずに約束事に取り組もうとしています。"ReduxPromise"を使わずに反応を処理する約束

return (
    <div> 
     <div>{this.props.weatherData.then(response => {return response.data.city.name})}</div> 
    </div> 
); 

は、しかし、私はこのエラーを取得する:

bundle.js:1212 Uncaught Error: Objects are not valid as a React child (found: [object Promise]). 

I console.log(response.data.city.name)が、私は結果の文字列を取得しない場合。 ReduxPromiseで

、私はこれをしなければならない。

<div>{this.props.weatherData.data.city.name}</div> 

しかし、私はReduxPromise

なしでそれをやってみたい:その後、私は唯一のコンポーネントでこれを返す必要が

const createStoreWithMiddleware = applyMiddleware(ReduxPromise)(createStore); 

ReduxPromiseなし、this.props.weatherDataは約束です。どのように私はコンポーネントでこれを処理するのですか?無限に出力

render(){ 
    if (!this.props.weatherData) { 
     return <div></div> 
    }; 

    this.props.weatherData.then(response => { 
     this.setState({ weatherData: response.data }); 
     console.log(this.state.weatherData.city.name); 
    }); 

市名:この下に行う

は無限ループを行います。

答えて

0

jsxのthis.props.weatherData.then(...)の戻り値をレンダリングしようとしています。これは、エラーメッセージが示すものです。代わりに、データをフェッチして状態に入れ、その状態に基づいてレンダリングします。

例:次に

componentWillReceiveProps(nextProps) { 
    if (!nextProps.weatherData) { 
     return; 
    }; 
    nextProps.weatherData.then(response => { 
      this.setState({ city: response.data.city.name }); 
    }); 
} 

:@TLaddへ

class WeatherDataComp extends React.Component { 
    state = { 
    weatherData: null 
    } 

    componentDidMount() { 
    this.props.weatherData.then(response => { 
     this.setState({ weatherData: response.data }) 
    }) 
    } 

    render() { 
    if (!this.props.weatherData) { 
     return null 
    } 
    return (
     <div>{this.state.weatherData.city.name}</div> 
    ) 
    } 

} 
+0

「キャッチしていないタイプのエラー:プロパティを読み取れません」、「ヌルの」 – trogne

+0

'this.props .weatherData'はcomponentDidMountを呼び出すときに存在しません – trogne

+0

props.weatherDataはweatherDataをフェッチする関数です。もしそうなら、マウントにはなぜそれがないのですか?なんらかの理由でそれができない場合は、componentWillReceivePropsライフサイクルメソッドを設定して、props.weatherDataが存在するかどうかを調べる必要があります。この時点で、フェッチをトリガーできます。これはレンダリングでthis.props.weatherDataを呼び出すときに同じエラーが発生するはずだったので、それは存在しません。 – TLadd

0

おかげで、私は、ライフサイクルの方法、すなわちcomponentWillReceivePropsを必要

render(){ 
    if (!this.props.weatherData) { 
     return <div></div> 
    }; 
    return (
     <div> 
      <div>{this.state.city}</div> 
     </div> 
    ); 
} 

そして無限ループのために、私はそれで、これが原因です: setState原因t再レンダリングするコンポーネントである場合は、.thenコールバックが呼び出されますので、setStateを再度呼び出してから再レンダリングしてください。

関連する問題