react本机数学动作不起作用

IT技术 reactjs react-native
2021-05-20 04:12:13

我在 React Native 项目上工作了一个多月。以前我从这个网站得到了解决方案。我希望这次我也能得到帮助。
这是我的小吃:Expo Snack 里面
有一个喜欢/不喜欢的系统。问题是每当你点击心形图标时,它会减去 1 的爱。当我“爱”这个帖子时,它不会增加 1。无论我做什么,它都会减少,“喜欢”或“不喜欢”。

我也在此处添加代码。



主程序

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) => {
    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) => {
        this.setState({ loveAction: responseJson.action });

        this.setState((state) => {
      const data = state.data.map((el) => {
        if(el.id === id) {
          el.isliked = !el.isliked;
      if(this.state.loveAction == "disliked"){
        el.loves = el.loves - 1;
      }else if(this.state.loveAction == "liked"){
        el.loves = el.loves + 1;
      }
        }
        return el;
      });
      const isPress = !state.isPress
      return { data, isPress };
    });

      }); 
  };
  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);



心.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;

所有 API 都运行良好。当我想增加或减少爱的数量时会出现问题。

请帮帮我。我是本机react的新手,所以请原谅我的问题

1个回答

你的第一个问题在这里

 this.setState({ loveAction: responseJson.action });

 this.setState((state) => {

this.setState是一个异步调用,它不会立即影响,但会告诉组件应该使用新状态再次渲染。每当你到达第二名时setState,你不一定会得到新的state

你可以做的是先在里面发送回调 setState

this.setState(
 { loveAction: responseJson.action,},
 () => this.state.data.map((el) => { ... }                
);

你的第二个问题(以及我没有详细说明map实施的原因

 if(el.id === id) {
          el.isliked = !el.isliked;

这是一个非法的状态修改,所以我会做类似的事情

this.setState(
 { loveAction: responseJson.action,},
 () => {
         let data = [...this.state.data]; // shallow copy state.data
         let elem = data.find(el => el.id === id); 
         data[indexOf(elem)] = {
                       ...elem,
                       isLiked: !elem.isLiked,
                       loves: this.state.loveAction == "disliked" ? elem.loves-- : elem.loves++
            };
         this.setState({ data }) 
    }
);