import React, { Component } from 'react';
import { connect } from 'react-redux';
class App extends Component {
state = {
isLogin: false
}
render() {
<div>
<h1>{isLogin "Logined" : "Not logged" }</h1>
<button onClick={this.props.handleLogin}>Login</button>
</div>
}
}
export default connect(
state => ({
user: state.user
}),
dispatch => ({
handleLogin: e => {
typeof this // "undefined"
this.setState({isLogin: true});
dispatch('LOGIN');
}
})
)(App);
我需要致电this.setState(...);
我使用此方法从Component
this
import React, { Component } from 'react';
import { connect } from 'react-redux';
class App extends Component {
state = {
isLogin: false
}
render() {
<div>
<h1>{isLogin "Logined" : "Not logged" }</h1>
<button onClick={this.props.handleLogin(this)}>Login</button>
</div>
}
}
export default connect(
state => ({
user: state.user
}),
dispatch => ({
handleLogin: _this => e => {
_this.setState({isLogin: true});
dispatch('LOGIN');
}
})
)(App);
我不认为这个决定是真的。 怎么做对了?
答案 0 :(得分:1)
使用redux的重点是拥有一个&#34;全局&#34;在商店里的状态。动作创建者返回一个对象,该对象被分派到reducer,然后reducer返回更新后的状态。 Thunk允许您延迟对操作对象的评估。
把这些放在一起,你可以这样做:
export default connect(
state => ({
user: state.user,
isLogin: state.isLogin,
}),
dispatch => ({
handleLogin: e => {
dispatch('LOGIN');
}
})
)(App);
现在您需要一个减速器来确定如何处理'LOGIN'
操作:
reducer = (state = {}, action) => {
switch (action) {
case 'LOGIN':
return Object.assign({}, state, {isLogin: true});
}
}
答案 1 :(得分:0)
您可以在组件内设置stet,然后调用prop。
import React, { Component } from 'react';
import { connect } from 'react-redux';
class App extends Component {
state = {
isLogin: false
}
handleLogin = () => {
this.setState({ isLogin: true })
this.props.handleLogin()
};
render() {
<div>
<h1>{isLogin "Logined" : "Not logged" }</h1>
<button onClick={this.handleLogin}>Login</button>
</div>
}
}
export default connect(
state => ({
user: state.user
}),
dispatch => ({
handleLogin: e => {
dispatch('LOGIN');
}
})
)(App);
在Realword示例中,您应该在Redux存储中设置loggedIn标志,而不是在Component中。
答案 2 :(得分:0)
您无法从App组件上下文访问this.setState。
如果我理解正确,您需要检查您是否在组件内登录。
我建议在state.user中使用一个名为: isAuthenticated 的属性,并将其用于您的逻辑。
this.props.user.isAuthenticated ? 'logged in' : 'not logged in'
或者你可以调用一个在上下文中进行两种更改的函数。
JSX
onClick={() => this.myOnClick()}
组件
myOnClick = () => {
this.setState({isLogin: true});
this.props.handleLogin();
}
有点不清楚你想要做什么但是:)