@ps

2016-04-13 17 views
0

kullanarak REST API çağrısı tarafından props.data bağlanırken "props" varsayılan değeri nasıl ayarlanır? Tepki bileşenindeki prop "verileri" için varsayılan değeri ayarlamaya çalışıyorum. Bu kodun "render" işlevinin bir kısmını tutmak istemiyorum, bunun yerine kurucunun ya da başka bir yaşam döngüsü olayının bir parçasını tutmak istiyorum. Ancak, "constructor" ı içinde tuttuğumda, "Salt okunur özelliği okuyamaz" hatasını atar. Ancak bunu diğer yaşam döngüsü olayında tuttuğumda, değişiklikler yansıtmıyor. Aşağıdakiler referans kodudur. Props.data'nın varsayılan değerini belirlemenin doğru yolu olduğundan emin değilsiniz.@ps

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> 
    ); 
    }; 
} 

Lütfen yardım edin.

cevap

0

senin bağlantı fonksiyonu bunu yapmanın kolay: açıklama için

connect(state => ({data: state.example.data || []})) 
İlgili konular