React組件間通訊-sub/pub機制

React生命週期第二個demo演示了兄弟組件的通訊,須要經過父組件,比較麻煩;下面介紹sub/pub機制來事項組件間通訊。html

項目結構:react

一、導包ios

npm i pubsub-js

 

二、UserSearch.jsxnpm

import React from 'react'
import PubSub from 'pubsub-js'

export default class UserSearch extends React.Component {
    state = {
        keyword: ''
    }

    render() {
        const { keyword, userList } = this.state
        return (
            <div>
                <h3>搜索用戶</h3>
                <input type="text" placeholder="請輸入搜索關鍵字" name="keyword" value={keyword} onChange={(e) => this.keywordInputOnChangeHandler(e)} />
                <input type="button" value="開始搜索" onClick={() => this.searchClickHandler()} />
            </div>
        )
    }

    keywordInputOnChangeHandler = (e) => {
        const keyword = e.target.value
        this.setState({ keyword })
    }

    searchClickHandler = () => {
        const { keyword } = this.state
        console.log(`keyword.trim()=${keyword.trim()}`)
        if (!keyword.trim()) return

        // publish a topic asynchronously
        PubSub.publish('search', keyword);
    }
}

 

三、UserList.jsxaxios

import React from 'react'
import PubSub from 'pubsub-js'
import Axios from 'axios'

export default class UserList extends React.Component {
    state = {
        userList: []
    }

    componentDidMount() {
        var mySubscriber = (msg, data) => {
            console.log(msg, data);
            console.log(`訂閱search,接收到消息:${data}`)
            this.doSearch(data)
        };

        console.log('UserList組件鉤子函數componentDidMount。。。');
        PubSub.subscribe('search', mySubscriber)
    }

    doSearch = (keyword) => {
        Axios.get(`http://localhost:4000/react-db-crud/user/search?keyword=${keyword}`)
            .then(res => {
                if (res.data.code == 0) {
                    const userList = res.data.data
                    console.log(`userList=${JSON.stringify(userList)}`)
                    this.setState({ userList })
                }
            })
    }

    render() {
        return (
            <div>
                {
                    this.state.userList.map(user => <p>{user.id + "--" + user.name + "--" + user.age}</p>)
                }
            </div>
        )
    }
}
相關文章
相關標籤/搜索