2017-06-19 64 views
0

我想根據從Redux收到的數據切換className值並傳遞給我的組件道具。但是,通過此代碼,我只是收到此錯誤:React + Redux道具不能及時加載

Uncaught TypeError: Cannot read property '0' of null 

它在我看來道具尚未收到。我聽說過使用默認/回退道具,但沒有成功實施它們。

我該如何解決這個問題?

calcROI() { 
    const myNum = (this.props.value1[0] + this.props.value2[0]); 

    let spanClassname = ''; 

    if(myNum < 0) { 
     spanClassname = 'my-class'; 
    } 

    const myNewNum = myNum.toFixed(0); 

    return { 
     spanClassname, 
     value : myNewNum 
    } 
} 

render() { 
    const {value3} = this.props; 
    const {spanClassname, value} = this.calcROI(); 

    return (
     <span className={spanClassname}> 
      My value is: {value + value3} 
     </span> 
    ); 

} 
+0

你想怎麼解決?你想使用默認值/回退值嗎? –

回答

1

一種解決方案是使用默認值,在這種情況下0聲明myNum的時候添加一些額外的條件:

// check if this.props.value1 and value2 exists and their lengths > 1 
 
const isMyNumExists = (this.props.value1 && this.props.value1.length > 1) 
 
    && (this.props.value2 && this.props.value2.length > 1); 
 

 
// if isMyNumExists is false or props is undefined, set myNum to 0 
 
const myNum = this.props && isMyNumExists ? 
 
    (this.props.value1[0] + this.props.value2[0]) : 0;

修訂

但是,如果您想要設置默認道具。你可以通過使用propTypes.defaultProps或者在mapStateToProps中設置默認道具來完成。第二種情況只有在你從狀態獲得value1和value2時纔有效,我相信你在做什麼。兩個示例的默認值都是[0]。

使用defaultProps:在mapStateToProps

// ... the rest of your import 
import PropTypes from 'prop-types'; 


class MyClass extends Component { 
    // ... your code here 
} 

// insert default value here... 
MyClass.defaultProps = { 
    value1: [0], 
    value2: [0] 
}; 

設置默認值:

const mapDispatchToProps = (store) => ({ 
    value1: store.value1 || [0], 
    value2: store.value2 || [0] 
}) 
+0

謝謝,這工作真棒,現在我知道該怎麼做。對此有任何想法嗎? https://stackoverflow.com/questions/38004703/set-default-props-for-a-react-component設置組件的默認道具...也許這不會工作,如果我從Redux收到道具?很好奇.. – fromspace

+1

@fromspace更新了我的答案 –

相關問題