反应本机状态无法正常工作

时间:2020-10-29 10:47:45

标签: reactjs react-native

我有这个组件:

import React, { Component } from "react";
import { Text, View, Image, TouchableOpacity } from "react-native";

import { styles } from "./styles";

import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { getAccounts } from "../../redux/user/selectors";

const UserMenuAccount = ({ active, account, balance }) => (
  <View style={styles.accountContainer}>
    <Image
      source={require("../../../assets/Usermenu/check.png")}
      style={[styles.icon, { opacity: active ? 1 : 0 }]}
    />
    <Text style={styles.text}>{account}</Text>
    <Text style={[styles.text, { opacity: 0.5 }]}>{balance} ETH</Text>
  </View>
);

class UserMenuAccounts extends Component {
  state = {
    userAccounts: [],
  };

  updateData  = index  => {
    const {userAccounts} = this.state
    const { GetAccounts } = this.props;
    const data =[...GetAccounts]
    data[index].isActive = data[index].isActive ? false : true
    this.setState({userAccounts:data})
  }

  render() {
    const { userAccounts } = this.state;
    const { GetAccounts } = this.props;
    return (
      <View>
        <Text style={{ opacity: 0.5, fontSize: 16, fontWeight: "bold" }}>
          Click to switch
        </Text>
        {userAccounts.map((users, index) => {
          return (
            <TouchableOpacity onPress={()=>this.updateData(index)}>
              <UserMenuAccount
                account={`${users}`}
                balance={0}
                active={active.isActive || false}
                key={index}
              />
            </TouchableOpacity>
          );
        })}
      </View>
    );
  }
}

const mapStateToProps = createStructuredSelector({
  GetAccounts: getAccounts,
});

export default connect(mapStateToProps, null)(UserMenuAccounts)

;

问题是我试图将StateActive设置为仅一个UserMenuAccout,但它对所有UserMenuAccout都设置为有效,请问我能为我提供解决方法吗?在此先感谢您,我是从redux商店中获取帐户并按照代码所示映射它们

1 个答案:

答案 0 :(得分:2)

尝试一下可能会帮助

class UserMenuAccounts extends Component {

  constructor(props){

    this.state = {
      userAccounts: props.GetAccounts,
    };

  }

  updateData(index){
    const data = […this.state.userAccounts];
     data[index].isActive = data[index].isActive? false: true;
    this.setState({userAccounts: data};
  }

  

  render() {
    const { userAccounts } = this.state;
    return (
      <View>
        <Text style={{ opacity: 0.5, fontSize: 16, fontWeight: "bold" }}>
          Click to switch
        </Text>
        {userAccounts.map((users, index) => {
          return (
            <TouchableOpacity onPress={()=> this.updateData(index)}>
              <UserMenuAccount
                account={`${users}`}
                balance={0}
                active={users.isActive || false}
                key={index}
              />
            </TouchableOpacity>
          );
        })}
      </View>
    );
  }
}