2017-07-17 91 views
0

簡單的問題,但我找不出解決方案。我在文本框上有一個簡單的字符計數器,可以按預期工作,但是,我在constructorcomponentWillReceiveProps中遇到了問題。我收到錯誤.length undefined.。如果長度未定義,我該如何解決這個問題?構造函數元素未定義並返回錯誤

constructor(props) { 
    super(props); 
    const profileCandidateCollection = props.profileCandidate; 
    const summary = profileCandidateCollection && profileCandidateCollection.summary; 
    const count = 3000 - (profileCandidateCollection && profileCandidateCollection.summary.length); 

    this.state = { 
    count: count, 
    }; 
} 

componentWillReceiveProps(nextProps) { 
    const profileCandidateCollection = nextProps.profileCandidate; 
    const summary = profileCandidateCollection && profileCandidateCollection.summary; 
    const count = 3000 - (profileCandidateCollection && profileCandidateCollection.summary.length); 

    this.setState({ 
    count: count, 
    }); 
} 
+0

你能添加一個代碼片段來重現錯誤嗎? – tugce

+0

'TypeError:無法讀取未定義的屬性「長度」 – bp123

回答

0

這似乎是工作的解決方案是使用if語句和贊成var下降const。我不知道爲什麼這是有效的。

if(summary == null) { 
    var count = 0; 
    } else { 
    var count = 3000 - (profileCandidateCollection && profileCandidateCollection.summary.length); 
    } 

    this.setState({ 
    count: count 
    }); 
    }