基本的Props传递数据与Props传递方法
父传子
1)、定义组件时,声明props形参:
class Person extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
姓名:{this.props.name}
);
}
}
2)、使用组件时,传入参数:
在子传父中, 父组件利用props传递方法给子组件,子组件回调这个方法的同时,将数据传递进去,使得父组件的相关方法得到回调,这个时候就可以把数据从子组件传递给父组件了
//1、父组件
class App extends React.Component {
constructor(){
super();
this.state={
titie:"Home"
}
}
changeData(str){
console.log("子传给了父亲:",str);
}
render = () => (
)
};
//2、子组件
class Home extends React.Component {
constructor(name){
super();
this.name=name;
this.state={
msg:"hello "
}
}
render = () => (
我是{this.props.title}
{this.state.msg+this.props.title}
this.props.myFun('HELLO dad')} />
)
}
ref的创建用xxx = React.createRef
在父组件中清除子组件的input输入框的value--->this.refs.form.reset()
ps:不过React官方文档建议不要过度依赖ref
React中的状态提升概括来说,就是将多个组件需要共享的状态提升到它们最近的父组件上,在父组件上改变这个状态然后通过props分发给子组件。
订阅: token=pubsub.subscribe(‘消息名’,回调函数(‘消息名’,数据))
发布: pubsub.publish(‘消息名’,数据)
清除指定订阅:pubsub.unsubscribe(token|‘消息名’);
清除所有:pubsub.unsubscribeAll()
//下载pubsub依赖
npm i pubsub-js -S
//导入依赖
import pubsub from 'pubsub-js'
child1组件中订阅一个事件
pubsub.subscribe('event1',()=>{alert('child1中订阅的事件')}
child2组件中发布这一事件
alertHandler=()=>{pubsub.publish('event1')}
注意:child1组件和child2组件都要引入pubsub 才可以使用
context状态树传参,即供应商消费者模式,跨组件通信方案
1.创建context对象 const GlobalContext = React.createContext()
2.给提供通信信息的组件加上供应商标签
import axios from 'axios';
import React, { PureComponent } from 'react'
const GlobalContext = React.createContext();//创建context对象
export default class App extends PureComponent {
constructor(){
super();
this.state={
filmdatas:[],
info:""
}
axios({
url:"test.json"
}).then(res=>{
this.setState({
filmdatas:res.data.data.films
})
})
}
render() {
return (
//供应商也就是父组件,用GlobalContext.Provider包裹,并在value里设置供应的数据和方法
{
this.setState({
info:value
})}
}}>
)}
}
class LeftShow extends PureComponent {
render() {
return(
//消费者也就是子组件,用GlobalContext.Consumer包裹,并用(value)=>{}的形式给子组件传参
{
(value)=>{
return(
{this.props.filmdatas.map(item=>
{
value.changeInfo(item.synopsis)
}}>
- 电影名:{item.name}
- 上映地:{item.nation}
- 时长:{item.runtime}分钟
)
}
)}}
)
}}
class RightShow extends PureComponent {
render() {
return (
{
(value)=>
{value.info}
}
)}}
共同点:
1.redux将数据保存在单一的store中,而mobx将数据保存在分散的多个store中
2.redux使用plain object保存数据,需要手动处理变化后的操作,mobx使用observable保存数据,数据变化后自动处理响应的操作。
3.redux使用的是不可变状态,意味着状态只是只读的,不能直接去修改它,而是应该返回一个新的状态,同时使用纯函数;mobx中的状态是可变的,可以直接对其进行修改。
4.mobx相对来说比较简单,在其中有很多的抽象,mobx使用的更多的是面向对象的思维,redux会比较复杂,因为其中的函数式编程思想掌握起来不是那么容易,同时需要借助一系列的中间件来处理异步和副作用。
5.mobx中有更多的抽象和封装,所以调试起来会更加复杂,同时结果也更难以预测,而redux提供可以进行时间回溯的开发工具,同时其纯函数以及更少的抽象,让调试变得更加容易。
mobx:面向对象思维、多个store、observable自动响应变化操作、mobx状态可变,直接修改、更多的抽象和封装,调试复杂,结果难以预测。
redux:函数式编程思想、单一store,plan object保存数据,手动处理变化后的操作、使用不可变状态,意味着状态只读,使用纯函数修改,返回的是一个新的状态、提供时间回溯的开发工具。