react-native redux无法访问和更新数据

时间:2018-11-12 15:30:00

标签: react-native redux

App.js
import React, { Component } from 'react';
import UserApp from './MainApplication';
import store from './store/index';
import { Provider } from 'react-redux';

class App extends Component {
  render() {
    return (
      <Provider store={store}>
        <UserApp />
      </Provider>
    );
  }
}

减速器:

import { ADD_USER } from '../actions/actionTypes';
//  import { initialState } from '../store/initialState';

const initialState = {
  id: 0,
  username: 'test',
  // email: '',
  // password: '',
  // otp: false,
  // otpColor: 'red',
  // otpStatus: 'Send OTP',
};

const addUser = (state = initialState, action) => {
  switch (action.type) {
    case ADD_USER:
      return Object.assign({}, state, {
        //id: action.payload.id,
        username: action.data,
        // email: action.email,
        // password: action.password,
        // otp: action.otp,
        // otpColor: action.otpColor,
        // otpStatus: action.otpStatus,
      });
  }
  return state;
};

export default addUser;

导出默认应用;

actionCreator:

import { ADD_USER, ADD_IMAGE, UPDATE_API, SEND_OTP } from './actionTypes';

let nextID = 0;

export const addUser = (data) => ({
  type: ADD_USER,
  id: (nextID += 1),
  data,
});

组件:

import React, { Component } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  Image,
  Button,
  TextInput,
} from 'react-native';
import { ImagePicker, Permissions } from 'expo';
//  import Icon from 'react-native-vector-icons/Ionicons';
import { connect } from 'react-redux';

class Users extends Component<Props> {
  constructor(props) {
    super(props);
    this.state = {
      image: null,
    };
  }
  _pickImage = async () => {
    const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
    if (status === 'granted') {
      let result = await ImagePicker.launchImageLibraryAsync({
        allowsEditing: true,
        aspect: [4, 3],
      });
      console.log(result);

      if (!result.cancelled) {
        this.setState({ image: result.uri });
      }
    } else {
      throw new Error('Camera roll permission not granted');
    }
  };

  render() {
    //const { fullName, email, password } = this.props.navigation.state.params;
    let { image } = this.state;

    return (
      <View style={styles.mainContainer}>
        <View styles={styles.container}>
          <TouchableOpacity style={styles.imageContainer}>
            image &&
            <Image source={{ uri: image }} style={styles.image} />
          </TouchableOpacity>
          <Button
            title={
              this.state.image === null
                ? 'Pick an image from camera roll'
                : 'Change Image'
            }
            onPress={this._pickImage}
          />

          <View>
            <Text style={styles.label}>Full Name: </Text>{' '}
            <TextInput
              placeholder={this.props.username}
              //onChangeText={email => this.setState({ email })}
              style={styles.input}
              returnKeyType="next"
              autoCapitalize="none"
              autoCorrect={false}
            />
            <Text style={styles.label}>Email: </Text>
            <TextInput
              placeholder={this.props.email}
              //onChangeText={email => this.setState({ email })}
              style={styles.input}
              returnKeyType="next"
              autoCapitalize="none"
              autoCorrect={false}
            />
          </View>
          <TouchableOpacity
            onPress={() => this.props.navigation.navigate('Home')}
            style={styles.btnContainer}>
            <Text style={styles.btn}>FINISH</Text>
          </TouchableOpacity>
        </View>
        <View>
          <Text>username: {this.props.username}</Text>
        </View>
      </View>
    );
  }
}
const mapStateToProps = state => ({
  username: state.username
});

导出默认的connect(mapStateToProps)(Users);

所需组件:

import React, { Component } from 'react';
import {
  View,
  StyleSheet,
  Text,
  TextInput,
  KeyboardAvoidingView,
  TouchableOpacity,
  ScrollView,
} from 'react-native';
import { connect } from 'react-redux';
// import { addUser } from '../reducers/addUser';
import { addUser } from '../actions';
import { ADD_USER } from '../actions/actionTypes';

class SignUp extends Component<Props> {
  constructor(props) {
    super(props);
    //  local state..
    this.state = {
      username: '',
      email: '',
      password: '',
      otp: false,
      otpColor: 'red',
      otpStatus: 'Send OTP',
    };
  }

  // addUser = (username) => {
  //   this.props.dispatch({ type: ADD_USER, username })
  // }

  render() {
    //const { navigate } = this.props.navigation;
    //const newUser = this.state;

    return (
      <View style={styles.mainContainer}>
        <View style={styles.header}>
          <View style={styles.createAccountContainer}>
            <Text style={styles.createAccount}> Create an account </Text>

            <View style={styles.underLineRight} />
          </View>
          <View style={styles.singInContainer}>
            {' '}
            <TouchableOpacity
              onPress={() => this.props.navigation.navigate('Login')}>
              <Text style={styles.signupHeader}> Sign In </Text>
            </TouchableOpacity>
            <View style={styles.underLineLeft} />
          </View>
        </View>
        <View style={styles.content}>
          <TextInput
            placeholder="FULL NAME"
            value={this.state.username}
            onChangeText={username => this.setState({ username })}
            //  onSubmitEditing={() => this.newUser.email.focus()}
            style={styles.input}
            returnKeyType="next"
            autoCapitalize="none"
            autoCorrect={false}
          />
          <View style={styles.emailContainer}>
            <TextInput
              placeholder="EMAIL"
              value={this.state.email}
              onChangeText={email => this.setState({ email })}
              //onSubmitEditing={() => this.newUser.password.focus()}
              keyboardType="email-address"
              style={[styles.input, { flex: 2 }]}
              returnKeyType="next"
              autoCapitalize="none"
              autoCorrect={false}
            />
            <TouchableOpacity
              value={this.state.email}
              onPress={() => {
                this.setState({
                  otp: true,
                  otpStatus: 'OTP Send',
                  otpColor: 'green',
                });
              }}
              style={styles.otpInput}>
              <Text style={{ color: this.state.otpColor }}>
                {this.props.otpStatus}
              </Text>
            </TouchableOpacity>
          </View>
          <TextInput
            placeholder="PASSWORD"
            value={this.state.password}
            //onChangeText={password => this.setState({ password })}
            style={styles.input}
            secureTextEntry={true}
            returnKeyType="go"
          />
          <TouchableOpacity
            onPress={() => {
              console.log(
                this.props.username + 'removeID TouchableOpacity(104)-- Users.js'
              );
              if (this.props.addNewUser()) this.props.navigation.navigate('Users');
            }}
            // onPress={() =>
            //   navigate('Users', {
            //     username: username,
            //     email: email,
            //     password: password,
            //   })
            // }
            style={styles.btnContainer}>
            <Text style={styles.btn}>Sign up</Text>
          </TouchableOpacity>
        </View>
        <View style={styles.orContainer}>
          <Text style={{ color: 'grey' }}>─────</Text>
          <Text style={styles.or}>Or</Text>
          <Text style={{ color: 'grey' }}>─────</Text>
        </View>

        <View style={styles.footer}>
          <TouchableOpacity style={styles.labelsGoogle}>
            <Text style={styles.btn}>google</Text>
          </TouchableOpacity>
          <TouchableOpacity style={styles.labelfacebook}>
            <Text style={styles.btn}>facebook</Text>
          </TouchableOpacity>
        </View>
        <View>
          <Text>username: {this.props.username}</Text>
        </View>
      </View>
    );
  }
}

// Add to the props of this class..
const mapStateToProps = state => {
  console.log(state);
  return {
    username: state.username,
    // email: state.email,
    // otp: state.otp,
    // otpColor: state.otpColor,
    // otpStatus: state.otpStatus,
  };
};

//  Add to the props of this class..
const mapDispatchToProps = (dispatch) => ({
    addNewUser: username => dispatch(addUser(username)),
    });

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(SignUp);

问题是, 无法将我的初始状态映射到组件。 无法更新状态。

我没有年长的人要问,我是一个初学者。做了大量的冲浪。项目一直正常工作,直到转换为redux。需要帮助。预先感谢。.

1 个答案:

答案 0 :(得分:0)

首先,您可以在componenet和

中调用操作方法
import { addUser } from '../actions'; // import

this.props.addUser(); // call method


export default connect(mapStateToProps, { addUser })(Users); // connect actions method

比您可以在下面设置reducers文件

export default (state = initialState, action) => {
  switch (action.type) {
    case ADD_USER:
      return Object.assign({}, state, {
        //id: action.payload.id,
        username: action.data,
        // email: action.email,
        // password: action.password,
        // otp: action.otp,
        // otpColor: action.otpColor,
        // otpStatus: action.otpStatus,
      });
  default:
        return state;
  }
};