2017-02-10 31 views
3

我已經開始在沒有Redux或Flux的情況下學習React,並且已經聽到很多關於Redux的信息,以及它是如何用於管理狀態的有利模式。我對它的理解是,應用程序的整個狀態都在我認爲位於React樹頂部的商店中。然後,各種兒童組件「訂閱」與他們相關的各種狀態。REDX的好處

這對我來說有些困惑,因爲我認爲React的核心結構已經以這種方式設置了?也就是說,如果我的組件有一個特定的狀態,然後將其傳遞給它的子組件,以便使用更深層次的React樹時,我需要將this.state.example或this.props.example添加到組件中。對我來說,用這種方法,我'訂閱'組件也是如此。

道歉,如果這不是正確的地方這樣的問題,但如果有人可以告訴我我在這裏錯過了什麼或者Redux的額外好處將會非常有幫助!

+4

您可能覺得此主題有用: https://github.com/reactjs/redux/issues/1287 gaearon是redux的創建者。他還寫了這篇文章: https://medium.com/@dan_abramov/you-might-not-need-redux-be46360cf367#.5lexgsyv6 – Conan

回答

4

你在訂閱部分是正確的,但是Redux的精彩和許多其他Flux狀態管理模式是你不必將屬性傳遞給子鏈,這樣你就可以更新子組件像這樣(你可以,如果你想,但不是需要):

function Parent() { 
    return <ChildOne color="red" /> 
} 

function ChildOne(props) { 
    return <ChildTwo color={props.color} /> 
} 

function ChildTwo(props) { 
    return <h1>The Color was: {props.color}</h1> 
} 

它可以讓你"dispatch"(一個終極版/通量項)的action的狀態商店更新爲準對象可能組件的屬性被訂閱。

該「連接」的有用庫是react-redux。它有很多功能,但我看到的主要是connect,它是一個更高級的組件(HOC),它用更多的邏輯「包裝」了組件,包括要訂閱的redux存儲庫的一部分。

所以上面的可以是:

export class Parent extends React.Component { 
    componentDidMount() { 
    this.props.dispatch(changeColor('red')); 
    } 
    render() { 
    return <ChildOne /> 
    } 
} 
export default connect((state) => ({ //This property is the redux store 
    parent: state.parent, 
}))(Parent) //higher order component that wraps the component with redux functionality 

function ChildOne(){ 
    return (
    <ChildTwo /> 
); 
} 

export function ChildTwo(props) { //will have childTwo bound in props object 
    return (
    <h1>The Color is: {props.childTwo.color} 
); 
} 
export default connect((state) => ({ //This property is the redux store 
    childTwo: state.childTwo, 
})) 

凡最大的區別是,你沒有從Parent下2級的色彩傳遞給ChildTwo,因爲它是「訂閱」到childTwo對象中redux存儲並將該狀態位連接到組件,因此對存儲的任何更改都會觸發組件從狀態更改中重新生成。

性能的傳遞和使用終極版將與這medium postPresentationContainer組件,其屬性的傳球是有道理的更多意義,因爲你只打算下一個子層深,容器組件處理邏輯,如Ajax請求或發送到零售店的零件等。

+0

謝謝扎克,很好的解釋,並給我一個關於好處的更好的想法! –

+0

很高興幫助!還有一個很好的地方可以學習更多關於redux的知識(以及什麼給了我那個時刻:Wes Bos的[learn redux](https://learnredux.com/)。如果你喜歡基於視頻的教程,非常豐富和優秀的! –

+2

您可能還想閱讀我共同撰寫的最近發佈的文章,該文章有助於在React應用程序中解釋Redux的優點:https://www.fullstackreact.com/articles/redux-with-mark-erikson/。 – markerikson