一、一個demo(https://www.reactjscn.com/docs/state-and-lifecycle.html)html
class Clock extends React.Component { constructor(props) { super(props); this.state = {date: new Date()}; } componentDidMount() { this.timerID = setInterval( () => this.tick(), 1000 ); } componentWillUnmount() { clearInterval(this.timerID); } tick() { this.setState({ date: new Date() }); } render() { return ( <div> <h1>Hello, world!</h1> <h2>It is {this.state.date.toLocaleTimeString()}.</h2> </div> ); } } ReactDOM.render( <Clock />, document.getElementById('root') );
二、demo: 兄弟組件之間通訊,使用到生命週期鉤子componentWillReceivePropsreact
項目結構:ios
demo效果:「搜索組件」傳遞keyword參數給父組件,而後父組件將keyword參數傳遞給「顯示子組件」axios
App.jsxui
import React from 'react' import UserSearch from '../user-search/UserSearch.jsx' import UserList from '../user-list/UserList.jsx' export default class App extends React.Component { constructor(props) { super(props) this.state = { keyword: '' } this.setKeyword = this.setKeyword.bind(this) } setKeyword(keyword) { console.log(`App組件setKeyword被調用, keyword=${keyword}`) this.setState({ keyword }) } render() { return ( <div> <UserSearch setKeyword={this.setKeyword} /> <UserList keyword={this.state.keyword} /> </div> ) } }
UserSearch.jsxthis
import React from 'react' import PropTypes from 'prop-types' export default class UserSearch extends React.Component { state = { keyword: '' } static propTypes = { setKeyword: PropTypes.func.isRequired } render() { const { keyword} = 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 this.props.setKeyword(keyword) } }
UserList.jsxspa
import React from 'react' import PropTypes from 'prop-types' import Axios from 'axios' export default class UserList extends React.Component { state = { userList: [] } componentWillReceiveProps(newProps) { const { keyword } = newProps 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> ) } } UserList.propTypes = { keyword: PropTypes.string.isRequired }