反应本机数学运算无法正常工作

时间:2020-06-22 18:07:53

标签: reactjs react-native

我从这里的上一个问题开始{@ {3}}

但是,我从那里的答案中得到了问题并更新了我的代码(我知道我没有解决非法的状态修改,主系统无法正常工作)。

App.js

import React, { Component } from 'react';
import {
  ActivityIndicator,
  Text,
  View,
  StyleSheet,
  FlatList,
  Alert,
  TouchableOpacity,
  ScrollView,
  TextInput
} from 'react-native';
import {
  Avatar,
  Card,
  Button,
  Divider,
  ListItem,
  Image
} from 'react-native-elements';
import Icon from 'react-native-vector-icons/FontAwesome';
import HTML from 'react-native-render-html';
import UserAvatar from 'react-native-user-avatar';
import { StackNavigator } from 'react-navigation';
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import Cookies from 'universal-cookie';
import Heart from './components/heart';

const cookies = new Cookies();

class HomeScreen extends React.Component {
  static navigationOptions = {
    title: '',
  };
  constructor(props) {
    super(props);
    this.state = {
      Loading: true,
      data: [],
      imageUrls: [],
      isPress: false,
      loveAction: '',
    };
  }

  fetchLeash(user) {
    return fetch('https://lishup.com/app/', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ user }),
    })
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({ data: responseJson });

        Promise.all(
          responseJson.map(({ images }) => this.fetchImage(images))
        ).then((imageUrls) => this.setState({ imageUrls }));
      })
      .catch((error) => {
        Alert.alert('error!');
      })
      .finally(() => {
        this.setState({ Loading: false });
      });
  }

  fetchImage(image) {
    return fetch('https://lishup.com/app/fetch-image.php', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ image }),
    })
      .then((response) => response.json())
      .then((responseJson) =>
        // Filter elements with empty string URLs, then app just the URL
        responseJson.filter(({ url }) => url).map(({ url }) => url)
      );
  }

  componentDidMount() {
    this.fetchLeash(cookies.get('user'));
    }
  heartOnPress = (id, writer) => {
    this.setState((state) => {
      const data = state.data.map((el) => {
        if(el.id === id) {
          if(el.isLiked == true){
              el.loves = el.loves - 1;
          } else {
              el.loves = el.loves + 1;
          }
          el.isliked = !el.isliked;
        }
        return el;
      });
      
      const isPress = !state.isPress
      return { data, isPress };
    });
    fetch('https://lishup.com/app/love.php', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ 
        id: id,
        user: cookies.get('user'),
        author: writer
         }),
    })
    .then((response) => response.json())
      .then((responseJson) => {  

    });
  };
  renderLeash = ({ item, index }) => (
    <View>
      <Card
        style={{
          height: 100,
          justifyContent: 'center',
          alignItems: 'center',
        }}>
        <ListItem
          leftAvatar={{
            title: item.user,
            source: { uri: item.userpic },
          }}
          title={item.user}
          subtitle={item.time}
          chevron
        />

        <Divider style={{ margin: 5, backgroundColor: 'white' }} />
        <HTML html={item.text} />
        <ScrollView
  horizontal={true}
  >
<View style={{flex:1, flexDirection:'row'}}>
        {this.state.imageUrls[index] && this.state.imageUrls[index].length
          ? this.state.imageUrls[index].map((uri) => (
              <Image
                source={{ uri }}
                style={{ flex:1, width: 500, height: 500, resizeMode: 'contain'}}
                PlaceholderContent={<ActivityIndicator />}
              />
            ))
          : null}
          </View>
          </ScrollView>
          
  <Text>{item.loves}</Text>
  <Text>{this.state.loveAction}</Text>
  <Heart isLiked={item.isliked} main={item.user} id={item.id} onPress={this.heartOnPress} />
      </Card>
    </View>
  );

  render() {
    if (this.state.Loading == true) {
    cookies.set('user', 'LishUp', { path: '/' });
      return (
        <ActivityIndicator
          size="large"
          style={{ marginTop: 100 }}
          color="#0000ff"
        />
      );
    } else {
      return (
        <View>
          <FlatList
            style={{ width: 400 }}
            data={this.state.data}
            keyExtractor={(item, idx) => idx}
            renderItem={this.renderLeash}
          />
        </View>
      );
    }
  }
}

const styles = StyleSheet.create({});

const RootStack = createStackNavigator(
  {
    Home: { screen: HomeScreen },
  },
  {
    initialRouteName: 'Home',
  }
);

export default createAppContainer(RootStack);

heart.js

import React from 'react';
import { View, TouchableOpacity } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';

const Heart = ({ isLiked, onPress, main, id }) => {
  return (
    <View>
      {isLiked ? (
        <TouchableOpacity onPress={() => onPress(id, main)}>
          <Icon name="heart" size={30} color="red" />
        </TouchableOpacity>
      ) : (
        <TouchableOpacity onPress={() => onPress(id, main)}>
          <Icon name="heart" size={30} color="grey" />
        </TouchableOpacity>
      )}
    </View>
  );
};

export default Heart;

正确的问题是:假设一个帖子中有2个爱情。我按了爱。它只是在数字2旁边加1,而不是进行加法。喜欢-它变成21而不是3

我不明白哪里出了错误,我是否会避免这种数学运算?

我的零食:React Native mathematical actions not working

2 个答案:

答案 0 :(得分:1)

这只是将您的“爱”当作字符串。首先用parseInt转换为数字:

if(el.isLiked == true){
              el.loves = parseInt(el.loves) - 1;
          } else {
              el.loves = parseInt(el.loves) + 1;
          }

答案 1 :(得分:1)

首先,您可以更改Heart组件

import React from 'react';
import { View, TouchableOpacity } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';

const Heart = ({ isLiked, onPress, main, id }) => {
  return (
    <View>
          <TouchableOpacity onPress={() => onPress(id, main)}>
          <Icon name="heart" size={30} color={isLiked?"red":"grey"} />
        </TouchableOpacity>
    </View>
  );
};

export default Heart;

您可以在像这样加减之前解析el.loves值

 el.loves = parseInt(el.loves) - 1;
el.loves = parseInt(el.loves) + 1;
相关问题