我正在重構無狀態的功能組件使用branch
和renderComponent
從recompose
。使用分支從重組
原來的組件看起來是這樣的:
const Icon = props => {
const { type, name } = props
let res
if (type === 'font') {
return (<FontIcon name={name} />)
} else if (type === 'svg') {
res = (<SvgIcon glyph={name} />)
}
return res
}
與分支組件看起來是這樣的:
const isFont = props => {
const { type } = props
return type === 'font'
}
const FontIconHoC = renderComponent(FontIcon)
const SvgIconHoC = renderComponent(SvgIcon)
const Icon = branch(isFont, FontIconHoC, SvgIconHoC)
Icon.propTypes = {
type: string,
name: string
}
export default Icon
我嘗試呈現組件使用:
<Icon name='crosshairs' type='font' />
產生的錯誤看起來像這樣:
invariant.js:44Uncaught Error: Icon(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.
問題的目標是弄清楚如何使用文檔中的分支。這是我爲自己做的探索性工作。雖然我同意分支的使用可能有限,但有一些來自'recompose'的實用程序,比如'withHandlers'和'withReducer',我真的很興奮。當將巨大的React組件重構爲更小的無狀態組件時,它確實幫助了我。 – vamsiampolu
我鼓勵你考慮使用模式重組鼓勵,而不必使用庫本身 –
@BradfordMedeiros這是一個可怕的答案。在圖書館遇到困難並不意味着你應該重新考慮圖書館。重構的目的是使代碼更具可讀性和可測性。 –