作者:只爱裙装 | 来源:互联网 | 2024-11-05 17:23
1.组件间通信
1.1 props
子->父组件->子
class Search extends Component {
handleClick = () => {
const { na
1.组件间通信
1.1 props
子->父组件->子
class Search extends Component {
handleClick = () => {
const { name } = this.state;
if (name) {
this.props.setSearchName(name);
}
};
import Search from "./search";
import Main from "./main";
class Users extends Component {
constructor(props) {
super(props);
this.state = {
searchName: ""
};
}
setSearchName = searchName => {
this.setState({
searchName
})
};
render() {
return (
);
}
}
export default Users;
import propTypes from "prop-types";
import "./index.less";
import axios from "axios";
class Main extends Component {
static propTypes = {
searchName: propTypes.string.isRequired
};
constructor(props) {
super(props);
this.state = {...};
}
componentWillReceiveProps(newProps) {
const { searchName } = newProps;
this.setState({... });
const url = `https://api.github.com/search/users?q=${searchName}`;
axios .get(url).then()
1.2 pubsubjs
yarn add pubsub-js
import PubSub from "pubsub-js";
class Search extends Component {
handleClick = () => {
const { name } = this.state;
if (name) {
// this.props.setSearchName(name);
// 发布消息(search)
PubSub.publish("search", name);
}
};
import PubSub from "pubsub-js";
class Main extends Component {
componentDidMount() {
// 订阅消息(search)
PubSub.subscribe("search", (msg, searchName) => {
console.log(msg, searchName);
this.setState({...});
const url = `https://api.github.com/search/users?q=${searchName}`;
axios.get(url).then();
1.3 redux