【发布时间】:2018-07-14 16:16:31
【问题描述】:
我正在尝试添加一些功能,根据用户是否至少有一个“信用”来启用或禁用按钮。我想使用逻辑 && 来确定是启用还是禁用按钮。父组件异步获取当前用户,这应该使组件能够访问用户模型和用户信用。
子组件:
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import SurveyList from './surveys/SurveyList';
class Dashboard extends Component {
render() {
console.log(this.props);
return (
<div>
<SurveyList />
<div className="fixed-action-btn">
{this.props.auth.credits &&
<Link to="/surveys/new" className="btn-floating btn-large red">
<i className="material-icons">add</i>
</Link>
}
<button className="btn-floating btn-large disabled red">
<i className="material-icons">add</i>
</button>
</div>
</div>
);
}
};
function mapStateToProps(state) {
return {
auth: state.auth
}
}
export default connect(mapStateToProps)(Dashboard);
父组件:
import React, { Component } from 'react';
import { BrowserRouter, Route } from 'react-router-dom';
import Header from './Header';
import { connect } from 'react-redux';
import * as actions from '../actions';
import Landing from './Landing';
import Dashboard from './Dashboard';
import NewList from './lists/NewList';
class App extends Component {
componentDidMount() {
this.props.fetchUser();
}
render() {
console.log(this.props);
return (
<div className="container">
<BrowserRouter>
<div>
<Header />
<Route exact path='/' component={Landing} />
<Route exact path='/surveys' component={Dashboard} />
<Route path='/surveys/new' component={NewList} />
</div>
</BrowserRouter>
</div>
);
}
};
export default connect(null, actions)(App);
动作:
export const fetchUser = () => async dispatch => {
const res = await axios.get('/api/currentUser')
dispatch({ type: FETCH_USER, payload: res.data});
};
【问题讨论】:
-
你的问题不是问题,它是对你想要做什么的描述,标题与你的描述没有任何关系。请先自己试一试,找出并解释问题所在以及我们可以在哪里提供帮助。
-
@DenniedeLange 标题如何与描述无关?标题描述了问题所在,描述解释了问题根源所在的代码。
-
@DenniedeLange 我在
组件中有一个 console.log(this.props) 行。当组件呈现时,控制台语句会触发两次。第一次触发时,this.props.auth.credits 为 Null(因此我将其命名为这样)。第二次触发时, this.props.auth.credits 不是 Null 并且具有我想要的值。我认为这是因为父组件进行了异步调用以获取当前用户(操作 sn-p),其中包含 auth.credits 部分。为了更好地表达这个问题,我如何等待该道具具有值或在渲染之前发出请求? -
那好多了,你现在正在解释什么是“道具”以及正在发生的事情。你对重新渲染是正确的,所以额外的检查就足够了
this.props.auth && this.props.auth.credits &&.. -
@DenniedeLange 是的,做到了。谢谢你。不确定如何将您的答案标记为已接受/正确
标签: reactjs redux react-router react-redux axios