我在我的React项目中使用redux。我在我的减速器中设置了初始状态
const initialState = {
isWarning: false,
};
我的react组件中有默认道具
LoginView.defaultProps = {
warning: false,
};
当然,我正在用渲染方法破坏道具
const { warning } = this.props;
这里有我组件中的代码
import React, { Component } from 'react';
import styled from 'styled-components';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import axios from '../../axios';
import Input from '../Input/Input';
import LoggedIn from '../LoggedIn/LoggedIn';
import * as actions from '../../store/actions';
const StyledWrapper = styled.div`
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
`;
const StyledTitle = styled.p`
color: #727272;
margin: 89px 0 73px 0;
font-size: 24px;
`;
const StyledButton = styled.button`
border: none;
border-radius: 6px;
background: #1de278;
height: 48px;
width: 397px;
color: #fff;
font-size: 18px;
cursor: pointer;
&:active,
&:focus {
outline: none;
}
`;
class LoginView extends Component {
state = {
email: '',
password: '',
};
onType = event => {
this.setState({ [event.target.id]: event.target.value });
};
onSubmit = (email, password) => {
axios
.post('api/v1/session', {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
email,
password,
})
// eslint-disable-next-line react/destructuring-assignment
.then(() => this.props.history.push('/'))
.catch(() => this.props.onLoginError(true));
};
render() {
const { email, password } = this.state;
const { warning } = this.props;
return (
<StyledWrapper>
{console.log(warning)}
<StyledTitle>Log in</StyledTitle>
<Input id="email" placeholderText="Email address"
setInputValue={this.onType} />
<Input
id="password"
placeholderText="Password"
setInputValue={this.onType}
type="password"
/>
<LoggedIn />
<StyledButton onClick={() => this.onSubmit(email,
password)}>Login</StyledButton>
</StyledWrapper>
);
}
}
const mapStateToProps = state => {
return { isWarning: state.login.isWarning };
};
const mapDispatchToProps = dispatch => {
return {
onLoginError: state => dispatch(actions.setErrorLogin(state)),
};
};
LoginView.propTypes = {
warning: PropTypes.bool,
};
LoginView.defaultProps = {
warning: false,
};
export default connect(
mapStateToProps,
mapDispatchToProps,
)(LoginView);
Redux开发人员工具将我的更新状态从false更改为true,但是我的警告具有false值。我认为这是带有默认道具的东西。您有什么想法可能是个问题吗?
答案 0 :(得分:2)
问题在这里:
const mapStateToProps = state => {
return { isWarning: state.login.isWarning };
};
应该是
const mapStateToProps = state => {
return { warning: state.login.isWarning };
};
由于该组件找不到warning
属性,因此将其设置为默认值,因此必须给它起相同的名称。