配置代理
方式一
在package.json 文件中添加如下代码
"proxy": "http://localhost:8091"
?? 说明:
- 优点:配置简单,前端请求资源时,可以不加任何前缀
- 缺点:只能配置一个地址
方式二
- 第一步:创建代理配置文件
在src下创建配置文件:src/setupProxy.js
- 编写setupProxy.js配置具体代理规则
const proxy = require('http-proxy-middleware')
module.exports = function (app) {
app.use(
proxy('/api1', {
target: 'http://localhost:8000',
changeOrigin: true,
pathRewrite: { '': '' }
}),
proxy('/api2', {
target: '',
changeOrigin: true,
pathRewrite: { '': '' }
}),
)
}
组件传参
父子组件传参
export default class App extends Component {
state = {
msg: "半夏天南星",
};
render() {
const { msg } = this.state;
return (
<div>
<Receive msg={msg}></Receive>
</div>
);
}
}
export default class index extends Component {
render() {
const { msg } = this.props;
return <h1>{msg ? msg : "等待数据发送"}</h1>;
}
}
子父组件传参
export default class App extends Component {
getSendMsg = (msg) => {
console.log(msg)
};
render() {
return (
<div>
<Send getSendMsg={this.getSendMsg}></Send>
</div>
);
}
}
export default class index extends Component {
sendMsg = () => {
const { value } = this.keyWord;
this.props.getSendMsg(value);
};
render() {
return (
<div>
<input type="text" ref={(c) => (this.keyWord = c)} />
<button onClick={this.sendMsg}>点击发送数据</button>
</div>
);
}
}
跨级组件通信
export default class App extends Component {
state = {
msg: "",
};
getSendMsg = (msg) => {
this.setState({ msg });
};
render() {
const { msg } = this.state;
return (
<div>
<Send getSendMsg={this.getSendMsg}></Send>
<Receive msg={msg}></Receive>
</div>
);
}
}
export default class index extends Component {
sendMsg = () => {
const { value } = this.keyWord;
this.props.getSendMsg(value);
};
render() {
return (
<div>
<input type="text" ref={(c) => (this.keyWord = c)} />
<button onClick={this.sendMsg}>点击发送数据</button>
</div>
);
}
}
export default class index extends Component {
render() {
const { msg } = this.props;
return <h1>{msg ? msg : "等待数据发送"}</h1>;
}
}
非嵌套组件通信(消息订阅与发布)
import React, { Component } from "react";
import PubSub from "pubsub-js";
export default class index extends Component {
sendMsg = () => {
const { value } = this.keyWord;
PubSub.publish("sendMsg", value);
};
render() {
return (
<div>
<input type="text" ref={(c) => (this.keyWord = c)} />
<button onClick={this.sendMsg}>点击发送数据</button>
</div>
);
}
}
import React, { Component } from "react";
import PubSub from "pubsub-js";
export default class index extends Component {
state = {
msg: "",
};
componentDidMount() {
this.token = PubSub.subscribe("sendMsg", (_, msg) => {
this.setState({ msg });
});
}
componentWillUnmount() {
PubSub.unsubscribe(this.token);
}
render() {
const { msg } = this.state;
return <h1>{msg ? msg : "等待数据发送"}</h1>;
}
}
-
publishSync – 同步发送消息 -
publish – 同步发送消息 -
subscribe – 订阅消息 -
unsubscribe – 卸载特定订阅 -
clearAllSubscriptions – 清除所有订阅
|