1.React 多层级 Router
1.webpack中output下面的publicPath和devServer的publicPath一致
//publicPath: '/'
2.React Router v4中设置多级路由
// <Route path="/settings/:direction(profilesettings|notificationsettings)" comp//onent={Settings}/>
<Provider store={store}>
<BrowserRouter>
<Layout>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/home" component={Home} />
<Route path="/about" component={About} />
<Route path="/user-profile" component={UserProfile} />
<Route path="/my-profile" component={MyProfile} />
<Route path="/settings/:direction(profilesettings|notificationsettings)" component={Settings}/>
<Route path="/not-found" component={NotFound} />
<Redirect exact path="*" to="/not-found"></Redirect>
</Switch>
</Layout>
</BrowserRouter>
</Provider>
3.在具体组件中
1)可以render的时候return一个Switch,其中匹配具体路由来加载,但是如果类似tab类的组件的话不好控制状态
<Switch>
<Route exact path="/settings/profilesettings" render={()=><div>profile</div>}/>
<Route exact path="/settings/notificationsettings" render={()=><div>test</div>}/>
</Switch>
2)通过参数来判断
2.1)这里需要引用withRouter来获取路由信息
import { withRouter} from 'react-router-dom';
export default withRouter(SettingsComponent)
2.2)通过this.props.match.params来获取然后根据不同逻辑处理
e.g:
render(){
let page = (this.props.match.params==="pageA")?1:2;
let comp = page===1?<ProfileSettingsForm/>:<NotificationForm/>
<div className="common-form">
<Link to="/home" className="form-back">Back</Link>
<div className="inner-form">
<NavBar>
<comp/>
</NavBar>
</div>
</div>;
}
2.关于子组件获取dispatch,通过调用reducer中的方法,将方法传递给子组件进行调用
export function mapStateToProps(storeState: StoreState) {
return {
userInfo: storeState.userInfo
}
}
export const mapDispatchToProps = {
getUserProfile,
updateUserProfile
}
mapDispatchToProps可以是一个对象也可以是一个funcion,上面是传递一个对象,把方法放里面,此案传递function:
const mapDispatchToProps = (dispatch,props)=>{
const initList = ()=>{
dispatch(getData());
}
const filterList = (name)=>{
dispatch(filterData(name));
}
是否可以将dispatch传递过去给子组件调用?
return {
initList,
filterList
}
}
const mapStateToProps = (state)=>{
const {listData} = state.ListReducer;
return {
listData:listData
}
}
const List = connect(
mapStateToProps,
mapDispatchToProps
)(ListComponent);
3.setState
网友评论