代码拉取完成,页面将自动刷新
<div ref = {( box )=>{ this.box = box }}></div>
console.log(this.box); // 获取dom
constructor()
state和props数据的初始化componentWillMount()
在组件即将被挂载到页面时执行(16.3已废弃)render()
渲染页面componentDidMount()
在组件被挂载到页面后执行,只在挂载时执行一次componentWillReceiveProps()
从父组件接收参数,且父组件重新执行了render函数,这个函数就会被执行shouldComponentUpdate()
在组件被更新之前执行 (return true 更新 , return false 不更新)componentWillUpdate()
shouldComponentUpdate返回true则会执行,返回false则不会执行render()
渲染页面componentDidUpdate()
在组件被更新之后执行componentWillUnmount()
在组件即将被页面剔除时执行除了render函数,其他所有的生命周期函数都可以没有
yarn add react-transition-group
js
import { CSSTransition } from 'react-transition-group';
class TodoList extends Component {
constructor(props) {
super(props);
this.state = {
show: true,
};
}
render() {
return (
<div>
<CSSTransition in={this.state.show} timeout={1000} appear={true} unmountOnExit classNames="mydemo">
<p>hello</p>
</CSSTransition>
<button onClick={this.toggle.bind(this)}>提交</button>
</div>
);
}
toggle() {
this.setState(() => ({
show: !this.state.show,
}));
}
}
css
.mydemo-enter,
.mydemo-appear {
opacity: 0;
}
.mydemo-enter-active,
.mydemo-appear-active {
opacity: 1;
transition: opacity 1s ease-in;
}
.mydemo-enter-done {
opacity: 1;
}
.mydemo-exit {
opacity: 1;
}
.mydemo-exit-active {
opacity: 0;
transition: opacity 1s ease-in;
}
.mydemo-exit-done {
opacity: 0;
}
yarn add antd
import { Input, Button, List } from 'antd';
import 'antd/dist/antd.css';
<Input placeholder="Basic usage"/>
<Button type="primary">提交</Button>
Redux = Reducer + Flux
yarn add redux
import store from './store/index';
import { changeInputAction } from './store/actionCreator';
class List extends Component {
constructor(props) {
super(props);
this.state = store.getState();
store.subscribe(this.storeChange.bind(this)); // store发生改变时,自动触发
}
render() {
return (
<div>
<input value={this.state.value} onChange={this.change.bind(this)} />
</div>
);
}
storeChange() {
this.setState(store.getState());
}
change(e) {
// const action = {
// type: 'change_input',
// value: e.target.value,
// };
const action = changeInputAction(e.target.value);
store.dispatch(action);
}
}
export default NewTodoList;
action的统一管理
export const changeInputAction = value => ({
type: 'change_input',
value,
});
import { createStore } from 'redux';
import reducer from './reducer';
const store = createStore(reducer, window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__());
export default store;
const defaultState = {
value: ''
};
export default (state = defaultState, action) => {
console.log(state, action);
let newState = JSON.parse(JSON.stringify(state)); // 深拷贝,不能直接修改state里的数据
if (action.type === 'change_input') {
newState.value = action.value;
}
return newState;
};
Redux-thunk
可以使action
可以返回函数,从而在store/actionCreator.js
中可以进行异步请求(axios)
npm install redux-thunk
或
yarn add redux-thunk
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import reducer from './reducer';
// window.__REDUX_DEVTOOLS_EXTENSION__ 可使用Redux DevTools插件
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;
// 使用Redux-thunk中间件
const enhancer = composeEnhancers(applyMiddleware(thunk));
// 创建store
const store = createStore(reducer, enhancer);
export default store;
import { Component, Fragment } from 'react';
import { List } from 'antd';
import store from './store/index';
import { getTodoList } from './store/actionCreator';
class TodoList extends Component {
constructor(props) {
super(props);
this.state = store.getState();
// store.subscribe(this.storeChange.bind(this)); // store发生改变时,自动触发
}
render() {
<Fragment>
<List bordered dataSource={this.state.list} renderItem={(item, index) => <List.Item> {item} </List.Item>} />
</Fragment>
}
componentDidMount() {
// 使用redux-thunk后,action可以返回函数,用于进行异步请求(axios)
const action = getTodoList();
store.dispatch(action);
}
}
export default TodoList;
import axios from 'axios';
export const initListAction = list => ({
type: 'init_list',
list,
});
// 使用redux-thunk后,action可以返回函数,用于进行异步请求(axios)
export const getTodoList = () => {
return dispatch => {
let list = [];
axios.get('https://www.fastmock.site/mock/0764b93cba70add273910b232c51aad8/development/api/getHotList').then(function (res) {
if (res.data.data.length > 0) {
for (const val of res.data.data) {
list.push(val.name);
}
}
const action = initListAction(list);
dispatch(action); // 将action传给store
});
};
};
const defaultState = {
list: []
};
export default (state = defaultState, action) => {
console.log(state, action);
let newState = JSON.parse(JSON.stringify(state)); // 深拷贝,不能直接修改state里的数据
if (action.type === 'init_list') {
newState.list = action.list;
}
return newState;
};
npm install redux-saga --save
或
yarn add redux-saga
src/store/index.js
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import createSagaMiddleware from 'redux-saga';
import reducer from './reducer';
import sagas from './sagas'; // 创建sagas.js
// window.__REDUX_DEVTOOLS_EXTENSION__ 可使用Redux DevTools插件
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;
// 创建Redux-saga中间件
const sagaMiddleware = createSagaMiddleware();
// 使用Redux-thunk中间件、Redux-saga中间件
const enhancer = composeEnhancers(applyMiddleware(thunk, sagaMiddleware));
// 创建store
const store = createStore(reducer, enhancer);
// 运行saga中间件
sagaMiddleware.run(sagas);
export default store;
src/store/sagas.js
import { put, takeEvery } from 'redux-saga/effects';
import axios from 'axios';
import { initListAction } from './actionCreator';
// generator 函数
function* mySaga() {
// 接收 store.dispatch() 传过来的action
// 接收到get_init_list的action后,会调用getInitList方法
// getInitList可以执行异步操作
yield takeEvery('get_init_list', getInitList);
}
function* getInitList() {
let list = [];
const res = yield axios.get('https://www.fastmock.site/mock/0764b93cba70add273910b232c51aad8/development/api/getHotList'); // 等待axios请求结束后,直接将结果赋值给res
if (res.data.data.length > 0) {
for (const val of res.data.data) {
list.push(val.name);
}
}
const action = initListAction(list);
yield put(action); // 类似于store.dispatch(action);
}
export default mySaga;
src/store/actionCreator.js
export const initListAction = list => ({
type: 'init_list',
list,
});
src/store/reducer.js
const defaultState = {
list: [],
};
export default (state = defaultState, action) => {
let newState = JSON.parse(JSON.stringify(state)); // 深拷贝,不能直接修改state里的数据
if (action.type === 'init_list') {
newState.list = action.list;
}
return newState;
};
import { Component, Fragment } from 'react'; // 占位符
import store from './store/index';
import { List } from 'antd';
import 'antd/dist/antd.css';
class NewTodoList extends Component {
constructor(props) {
super(props);
this.state = store.getState();
store.subscribe(this.storeChange.bind(this)); // store发生改变时,自动触发
}
render() {
return (
<Fragment>
<List bordered dataSource={this.state.list} renderItem={(item, index) => <List.Item> {item} </List.Item>} />
</Fragment>
);
}
componentDidMount() {
const action = {
type: 'get_init_list',
};
store.dispatch(action); // action不仅会被reducer接收,还会被redux-saga接收
}
storeChange() {
this.setState(store.getState());
}
}
export default NewTodoList;
npm install react-redux --save
或
yarn add react-redux
provider包裹在根组件外层,使所有的子组件都可以拿到state
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import './index.css';
import store from './store';
import App from './App';
import reportWebVitals from './reportWebVitals';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
reportWebVitals();
src/List.js
import { Component, Fragment } from 'react';
import { connect } from 'react-redux';
class List extends Component {
render() {
return (
<Fragment>
<div>
<label htmlFor="input">输入内容</label>
<input id="input" type="text" value={this.props.value} onChange={this.props.changeInput} />
</div>
</Fragment>
);
}
}
// 把state数据映射到props中
// 这样在jsx中就可以用this.props.value来代替this.state.value获取值
const mapStateToProps = state => {
return {
value: state.value,
};
};
// 把store.disptch()挂载到props上
// 这样在jsx中就可以用this.props.changeInput来代替store.disptch()改变store里的数据
const mapDispatchToProps = disptch => {
return {
changeInput(e){
const action = {
type: 'change_input',
value: e.target.value,
};
disptch(action);
}
};
};
export default connect(mapStateToProps, mapDispatchToProps)(List); // List连接store
src/store/reducer.js
const defaultState = {
value: ''
};
export default (state = defaultState, action) => {
let newState = JSON.parse(JSON.stringify(state)); // 深拷贝,不能直接修改state里的数据
if (action.type === 'change_input') {
newState.value = action.value;
}
return newState;
};
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。