2016-04-13 4 views
0

反応コンポーネントのprop "data"のデフォルト値を設定しようとしています。私はこのコードを "レンダリング"機能の一部にしたくないのですが、代わりにコンストラクタや他のライフサイクルイベントの一部にしておきたいと思います。しかし、私は内部 "コンストラクタ"を保持しているときにそれが "読み取り専用プロパティに割り当てることはできません"エラーをスローすることに気付きました。しかし、他のライフサイクル・イベントでそれを保持すると、変更は反映されません。以下は参考のためのコードです。 props.dataのデフォルト値を設定する正しい方法がわからない。@connectを使用してprops.dataがREST API呼び出しによってバインドされているときに、 "props"のデフォルト値を設定する方法

import React from "react"; 
import {connect} from 'react-redux'; 
import Country from "./Country"; 

@connect(state => ({data: state.example.data})) 
export default class Countries extends React.Component { 

    constructor(props) { 
    props.data = props.data || []; //This throws exception that Cannot assign to read only property 
    super(props); 
    } 
    componentWillMount (props) { 
    console.log("componentWillMount"); 
    props.data = props.data || []; //This change doesn't solve the issue. 
    } 
    componentDidMount (props) { 
    console.log("componentDidMount"); 
    props.data = props.data || []; //Since render function fail therefore execution flow doesn't reach here. 
    } 
    componentWillReceiveProps (props) { 
    console.log("componentWillReceiveProps"); 
    props.data = props.data || []; //Since render function fail therefore execution flow doesn't reach here. 
    } 
    render() { 

    const data = this.props.data; //This needs constructor or lifecycle method to set default value. 
    //const data = this.props.data || []; //This works 

    console.log("Countries this.props "+ JSON.stringify(this.props)); 
    return (<div className='container'> 
     <table className='table table-bordered table-striped'> 
     <thead> 
     <tr> 
      <th>Name</th> 
      <th>Capital</th> 
      <th>Population</th> 
      <th>Domain</th> 
     </tr> 
     </thead> 
     <tbody> 
     { data.map(country => { return (<Country key={country.name} country={country} />)})} //This throws exception as "data" is undefined at beginning. therefor need to set default value. 
     </tbody> 
     </table> 
    </div> 
    ); 
    }; 
} 

助けてください。

答えて

1

リアクション小道具はコンポーネント作成時にフリーズします。 https://facebook.github.io/react/blog/2015/10/07/react-v0.14.html#breaking-changesを参照してください。

ajax呼び出しを実行し、その要求の結果を使用してpropsでコンポーネントを作成するか、setStateを使用してコンポーネントを変更するか、要素を複製する必要があります。

+0

説明してくれてありがとう。非常に役立ちます。 – joy

0

あなたコネクト機能でこれを行う最も簡単:

connect(state => ({data: state.example.data || []})) 
関連する問題