react基础知识
更新数据的this.setState()
在日常使用中,都是直接就this.setState(),里面包裹着一个对象然后直接的更新好数据例如:1
this.setState({isTrue:true});
然后,在一些场景中,由于数据量大,保存的时候会因为没存储完就立马去调用下一步操作,这个时候,我也尝试了 async + await,ES7中异步的操作,但是还是没啥变化,最后在查阅资料的过程中,发现this.setState()还可以有函数的参数,例如:1
2
3this.setState({isTrue:true},()=> {
// 在这里做一些存储完数据后的操作
});
在react后续的版本中,setState方法还可以是函数的形式,例如:1
2
3
4
5
6this.setState(
// 这样也能达到更新值的目的,两个参数,在一些异步的场景说会用到
(prevState, props) => (
{ count: prevState.count + 1 }
)
);
{true?true:false}(三元表达式) || &&
1 | /* |
跳转路由的方式
在日常的框架中,都有一个是直接就跳转能够存储到,还有一个replace直接不能后退,如下写法:
1 | this.props.router.push |
路由的写法
在接触的移动端中,路由用的4,写法感觉和之前Vue的路由大同小异,如下:
在引入入口的render中就开始书写上router,如下:1
2
3
4
5
6
7
8
9
10
11
12// Stores 和 Routes 的初始化
// 使用React-Router 3 效果会更好
import { Router, hashHistory } from "react-router";
// 导入Provider
import { Provider } from "mobx-react";
const rootEl = document.getElementById("root");
render(
<Provider {...Stores}>
<Router history={hashHistory} routes={routes} />
</Provider>,
rootEl
);
接下来则是引入路由的路径1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41 import App from "./App";
import { uservistIng } from './biz/home/index/userVistIngServ'
function setTitle(title) {
window.document.title = title;
}
// 进入路由之前的处理,检查是否已登录
const beforeEnter = async (nextState, replace, next) => {
await uservisits();
next()
}
async function uservisits() {
await uservistIng();
}
export default [
{
path: "/",
component: App,
indexRoute: { onEnter: (nextState, replace) => replace("/home") },
childRoutes: [
{
path: "home",
getComponent: (nextState, cb) => {
setTitle("长安汽车尊享服务");
import("biz/home/index/IndexView").then(x => {
cb(null, x.default);
});
},
onEnter: beforeEnter
},
{
path: "chat",
title: "VIP服务室",
getComponent: (nextState, cb) => {
import("biz/home/chat/IndexView").then(x => {
cb(null, x.default);
});
},
onEnter: beforeEnter
}
]
}