A, passing through the props
- Common data on the parent component, specific data on their own internal components (state)
- props can pass through the general data and the function data, only one layer is transmitted, i.e. transmission unidirectional monolayers
- General Data
Parent component subassembly to pass data - Data read> subassembly
- Function data
Subassembly components pass data to the parent -> child component calls the function
to sum up:
Sons communication between components, the use of props property. Wherein only be transferred from the parent element to the sub-assembly (unidirectional). If the sub-assembly to be transferred to the parent data to the assembly only by means of a callback function.
Brothers components can not communicate directly, communication can only be done through shared indirect parent component.
Props used for communication is applicable to many levels of the component is not, the data transfer is not very complicated situation.
Second, the message subscription (subscribe) - release (publish) mechanism
Feed side of the received data message (Subscribe) who publish data (generation) side release (publish) are for the message.
This way we can communicate across the hierarchy. Any two components so that communication becomes possible.
In JavaScript, use third-party libraries PubSubJS complete message subscription - release mechanism.
Documentation: https://github.com/mroderick/PubSubJS
PubSubJS use:
1. Install
npm install pubsub-js --save
2. Use
// introduced import PubSub from 'pubsub-js'
// 订阅 PubSub.subscribe('delete', function(msg, data){ });
// announced PubSub.publish ( 'delete', data)
The main API
PubSub.subscribe(topic, callback)
Subscribe to news
parameter:
topic
Message Name
callback
Callback handler when a message is received, accepts two parameters:
msg
Message Name
data
Data publisher issued
return value
Returns a token, it can be used to unsubscribe
PubSub.publish(topic, data)
make an announcement
parameter:
topic
Message name, message name news publishers and subscribers must be defined as, otherwise not receive messages
data
Data publisher issued
PubSub.unsubscribe(token)
Message to cancel a subscription
parameter:
token
subscribe () Returns the value of
Three, Redux
This would not introduce too much, the famous redux, a specialized independent state for management of libraries. React to complete the combination of large and complex projects.