gpt4 book ai didi

reactjs - Redux - 在 TextInput 组件中输入内容后状态不会正确更新

转载 作者:行者123 更新时间:2023-12-04 08:22:29 25 4
gpt4 key购买 nike

我正确地完成了 redux 教程的所有说明。但是运行程序后,当我尝试在电子邮件或密码中输入一个值时 TextInput , 值不放在里面,邮件输入立即清空。我不知道我在哪里做错了。但我认为该操作无法正常工作。我希望你能指导我。

在 Action 目录 > index.js

import { EMAIL_CHANGED, PASS_CHANGED, USER_LOGIN_ATEMT, USER_LOGIN_SUCCESS, USER_LOGIN_FAILED } from "./types";
export const emailChanged = (text) => {
return {
type: EMAIL_CHANGED,
payload: text
}
}
export const passChanged = (text) => {
return {
type: PASS_CHANGED,
payload: text
}
}
export const loginUser = ({ email, pass }) => {
return (dispatch) => {
dispatch({ type: USER_LOGIN_ATEMT });
fetch('', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: email,
password: pass
})
}).then((response) => response.json()).
then((responseJson) => {
if (responseJson === 'Data Matched') {
loginUserSuccess(dispatch);
} else {
loginUserFailed(dispatch);
}
}).catch((error) => { alert(error) });
}
}
const loginUserSuccess = (dispatch) => {
dispatch({ type: USER_LOGIN_SUCCESS });
}

const loginUserFailed = (dispatch) => {
dispatch({ type: USER_LOGIN_FAILED });
}

在 Action 目录 > types.js
export const EMAIL_CHANGED = 'EMAIL_CHANGED';
export const PASS_CHANGED = 'PASS_CHANGED';
export const USER_LOGIN_ATEMT = 'USER_LOGIN_ATEMT';
export const USER_LOGIN_SUCCESS = 'USER_LOGIN_SUCCESS';
export const USER_LOGIN_FAILED = 'USER_LOGIN_FAILED';

在组件目录> LoginForm.js
import React, { Component } from 'react';
import { View, TextInput, Text, FlatList, ActivityIndicator, TouchableOpacity } from 'react-native';
import { connect } from 'react-redux';
import { emailChanged, passChanged, loginUser } from '../actions/index';

class LoginForm extends Component {
onEmailChange(text) {
this.props.emailChanged(text)
}
onPassChange(text) {
this.props.passChanged(text)
}
onLoginUser() {
const { email, pass } = this.props;
this.loginUser({ email, pass });
}
renderButton() {
if (this.props.loading) {
return (<ActivityIndicator size="large" color="#0000ff" />);
} else {
return (
<TouchableOpacity onPress={() => this.onLoginUser.bind(this)} >
<Text>Continue...</Text>
</TouchableOpacity>
)
}
}
render() {
return (
<View>
<TextInput
placeholder="Email"
onChangeText={() => this.onEmailChange.bind(this)}
value={this.props.email}
/>
<TextInput
placeholder="Pass"
onChangeText={() => this.onPassChange.bind(this)}
secureTextEntry={true}
value={this.props.pass}
/>
<Text>{this.props.error}</Text>
{this.renderButton()}
</View>
);
}
}


const mapStateToProps = state => {
return {
email: state.auth.email,
pass: state.auth.pass,
loading: state.auth.loading,
error: state.auth.error
}
}


export default connect(mapStateToProps, { emailChanged, passChanged, loginUser })(LoginForm);

在 reducers 目录 > AuthReducer.js
import { EMAIL_CHANGED, PASS_CHANGED, USER_LOGIN_ATEMT, USER_LOGIN_SUCCESS, USER_LOGIN_FAILED } from '../actions/types';
const initialState = {
email: '',
pass: '',
loading: false,
error: ''
}
const AuthReducer = (state = initialState, action) => {
console.log(action);
switch (action.type) {
case EMAIL_CHANGED:
return { ...state,
email: state.email.concat({
key: Math.random(),
value: action.payload
})
}
case PASS_CHANGED:
return { ...state, pass: action.payload }
case USER_LOGIN_ATEMT:
return { ...state, loading: true }
case USER_LOGIN_SUCCESS:
return { ...state, ...initialState }
case USER_LOGIN_FAILED:
return { ...state, loading: false, pass: '', error: 'اشتباه وارد شده است' }
default:
return state;
}
}
export default AuthReducer;

在 reducers 目录 > index.js
import { combineReducers } from 'redux';
import AuthReducer from '../reducers/AuthReducer';
const reducers = combineReducers({
auth: AuthReducer
});
export default reducers;

在 App.js 中
import React, { Component } from 'react';
import { View, TextInput, Text, FlatList, Pressable } from 'react-native';
import { Provider } from 'react-redux';
import { applyMiddleware, createStore } from 'redux';
import reducers from './reducers/index';
import LoginForm from './components/LoginForm';
import ReduxThunk from 'redux-thunk';

export default class App extends Component {
render() {
return (
<Provider store={createStore(reducers, {}, applyMiddleware(ReduxThunk))}>
<LoginForm />
</Provider>
);
}
}

在 index.js 中
import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';

AppRegistry.registerComponent(appName, () => App);

我的 package.json
"react": "16.13.1",
"react-native": "0.63.4",
"react-redux": "^7.2.2",
"redux": "^4.0.5",
"redux-thunk": "^2.3.0"

最佳答案

问题email最初是一个空字符串,当您发送 EMAIL_CHANGED你试图用键连接一个对象 keyvalue给它。您的组件仅访问 state.auth.email .我绝对确定应该在某处抛出错误。 onChangeText 文本输入中的值是整个值,而不是增量,因此您不应该连接或附加任何内容,只需完全替换现有的电子邮件状态(实际上,这部分是正确的密码)。
附加处理程序的方式也存在问题。

onChangeText={() => this.onEmailChange.bind(this)}
这会删除 onChangeText值并将 undefined 传递给您的处理程序。
解决方案
更新 reducer 案例以正确更新 email值(value)。
case EMAIL_CHANGED:
return {
...state,
email: action.payload,
}
更新处理程序以使用更改的值。
onChangeText={this.onEmailChange.bind(this)}
提示:要保存 this 的绑定(bind),您可以在 constructor 中执行此操作。或使用箭头功能。
onEmailChange = (text) => {
this.props.emailChanged(text)
}

...

onChangeText={this.onEmailChange}
第二个提示:您可以直接将传递的处理程序附加到输入并保存函数声明和 this捆绑。
onChangeText={this.props.onEmailChange}
如果由于某种原因您需要随机键值(随机值是较差的键/ID,因为它们不能保证是唯一的)然后更新如下:
提供有效的初始状态
const initialState = {
email: {}, // <-- empty object, provides object to destructure from in UI
...
}
完全替换 email目的
case EMAIL_CHANGED:
return { ...state,
email: {
key: Math.random(),
value: action.payload
}
}
在组件中正确访问电子邮件值
const mapStateToProps = state => {
return {
email: state.auth.email.value, // <-- get the email value
...
}
}

关于reactjs - Redux - 在 TextInput 组件中输入内容后状态不会正确更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65432940/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com