路线内的反应上下文
React context inside Route
我正在尝试在 React Route 中获取上下文变量。这是我的代码
<Switch>
<Route exact path="/" component={Home} />
<Route path="/home/:loc" render={(props)=> {
<AppContext.Consumer>
{
context=><Home context={context} />
}
</AppContext.Consumer>
}} />
</Switch>
这是我的AppContext.js
import React from 'react';
export const AppContext = React.createContext();
这就是我设置上下文的方式
<AppContext.Provider value={this.state}>
<div className="App">
<Header />
<Content />
<Footer />
</div>
</AppContext.Provider>
这是我遇到的错误
Expected an assignment or function call and instead saw an expression no-unused-expressions
知道这里出了什么问题吗?
Expected an assignment or function call and instead saw an expression no-unused-expressions
不是错误,而是 linter 警告。 no-unused-expressions
规则通常表示由于开发人员的错误,代码可能无法按预期工作。
已发布代码的问题是 render
箭头函数没有 return 任何东西。
应该是:
<Route path="/home/:loc" render={(props)=> (
<AppContext.Consumer>
{
context=><Home context={context} />
}
</AppContext.Consumer>
)} />
=> {...}
需要显式 return,而 => (...)
是隐式 return.
我正在尝试在 React Route 中获取上下文变量。这是我的代码
<Switch>
<Route exact path="/" component={Home} />
<Route path="/home/:loc" render={(props)=> {
<AppContext.Consumer>
{
context=><Home context={context} />
}
</AppContext.Consumer>
}} />
</Switch>
这是我的AppContext.js
import React from 'react';
export const AppContext = React.createContext();
这就是我设置上下文的方式
<AppContext.Provider value={this.state}>
<div className="App">
<Header />
<Content />
<Footer />
</div>
</AppContext.Provider>
这是我遇到的错误
Expected an assignment or function call and instead saw an expression no-unused-expressions
知道这里出了什么问题吗?
Expected an assignment or function call and instead saw an expression no-unused-expressions
不是错误,而是 linter 警告。 no-unused-expressions
规则通常表示由于开发人员的错误,代码可能无法按预期工作。
已发布代码的问题是 render
箭头函数没有 return 任何东西。
应该是:
<Route path="/home/:loc" render={(props)=> (
<AppContext.Consumer>
{
context=><Home context={context} />
}
</AppContext.Consumer>
)} />
=> {...}
需要显式 return,而 => (...)
是隐式 return.