你在訂閱部分是正確的,但是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 postPresentation
和Container
組件,其屬性的傳球是有道理的更多意義,因爲你只打算下一個子層深,容器組件處理邏輯,如Ajax請求或發送到零售店的零件等。
您可能覺得此主題有用: https://github.com/reactjs/redux/issues/1287 gaearon是redux的創建者。他還寫了這篇文章: https://medium.com/@dan_abramov/you-might-not-need-redux-be46360cf367#.5lexgsyv6 – Conan