【问题标题】:Can't find variable in React Native在 React Native 中找不到变量
【发布时间】:2021-05-31 10:26:41
【问题描述】:

我正在尝试将教程改编为我自己的“照片制作应用程序”。但我不知何故难以将 SQLite 实施到我的项目中,我不明白错误以及为什么会得到它。

我有以下减速器:

import { ADD_PHOTO, SET_OBJECTS } from "./photo-actions";
import PhotoObject from "../models/photoObject";

const initialState = {
  photos: [],
};

export default (state = initialState, action) => {
  switch (action.type) {
    case SET_OBJECTS:
      return {
        objects: action.objects.map(
          (ob) => new Object(ob.id.toString(), ob.title, ob.imageUri)
        ),
      };
    case ADD_PHOTO:
      const newObject = new PhotoObject(
        action.photoData.id,
        action.photoData.title,
        action.photoData.image,
        action.photoData.description
      );
      console.log("Ich bin das newObject aus photo-reducer.js");
      console.log(newObject);
      return {
        photos: state.photos.concat(newObject), //<---------this is where I assume the error
      };
    default:
      return state;
  }
};

我的错误日志的最后一点如下所示:

Ich bin das newObject aus photo-reducer.js
PhotoObject {
  "description": "cool",
  "id": 1,
  "imageUri": undefined,
  "title": "Dog",
}
In photo-actions.js--> addPhoto wurde dispatch ausgeführt

ReferenceError: Can't find variable: state //<----- it says it can't find the state but I'm sure I defined it correctly, didn't I?

This error is located at:
    in Gallery (created by SceneView)
    in SceneView (created by CardContainer)
    in RCTView (at View.js:34)
    in View (created by CardContainer)
    in RCTView (at View.js:34)

这是我的行动

...

export const addPhoto = (title, image, description) => {
  return async (dispatch) => {
    const fileName = image.split("/").pop();
    const newPath = FileSystem.documentDirectory + fileName;

    try {
      await FileSystem.moveAsync({
        from: image,
        to: newPath,
      });
      const dbResult = await insertObject(
        title,
        newPath,
        "dummyDescription aus photo-actions",
        "locationTest aus photo-actions",
        10
      );
      console.log("Ich bin das dbResult aus photo-actions.js-->addPhoto");
      console.log(dbResult);
      dispatch({
        type: ADD_PHOTO,
        photoData: {
          id: dbResult.insertId,
          title: title,
          imageUri: newPath,
          description: description,
        },
      });
      console.log("In photo-actions.js--> addPhoto wurde dispatch ausgeführt");
    } catch (err) {
      console.log(err);
      throw err;
    }
  };
};

export const loadObjects = () => {
  return async (dispatch) => {
    try {
      const dbResult = await fetchObjects();
      dispatch({ type: SET_OBJECTS, objects: dbResult.rows._array });
    } catch (err) {
      throw err;
    }
  };
};

这是我要在其中使用状态的组件:

...
const Gallery = (props) => {
  const photos = useSelector((state) => state.photos.photos);
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(objectActions.loadObjects());
  }, [dispatch]);

  return (
    <FlatList
      data={photos}
      keyExtractor={(item) => item.id}
      renderItem={(itemData) => (
...

问题是通过使用 expo ImagePicker 并希望存储获取的数据开始的:

...
  const savePhotoHandler = () => {
    dispatch(
      photosActions.addPhoto(titleValue, selectedImage, descriptionValue)
    );
    props.navigation.navigate("Gallery");<--------------this command leads to the component where I receive the error when I want to grab the state
  };
...

【问题讨论】:

  • 根据您的日志,看起来错误发生在您认为的位置之后。看起来整个addPhoto 都正确通过。除了useSelector 中的引用之外,Gallery 屏幕上是否还有其他对 state 的引用?
  • 我在你的减速器中发现了一个错误,我会写一个答案,但我不确定它与特定的错误消息“找不到变量:状态”有何关系

标签: javascript reactjs react-native sqlite redux


【解决方案1】:

可序列化状态

not a good idea 在状态中存储一个不可序列化的值,例如 PhotoObject 类实例。我只会存储来自action.payload 的原始数据,并在您从状态中选择它时将其构造为PhotoObject 实例。存储不可序列化的对象会干扰 Redux 开发工具。

返回不完整状态

reducer 必须总是返回一个完整的状态。您的 photos 减速器有两个属性:objectsphotos。您的所有案例都返回一个只有一个属性的对象并删除另一个。

return {
  objects: action.objects.map(
    (ob) => new Object(ob.id.toString(), ob.title, ob.imageUri)
  ),
};
return {
  photos: state.photos.concat(newObject),
};

您需要使用...state 来返回您未更新的其他属性。

新对象()

我不知道你在这里做什么:

new Object(ob.id.toString(), ob.title, ob.imageUri)

Object constructor 只接受一个参数。

我想知道这段代码中是否有一堆拼写错误,您的意思是new PhotoObject,并且您还打算设置属性photos而不是objects

也许这行得通?

const initialState = {
  photos: [],
};

export default (state = initialState, action) => {
  switch (action.type) {
    case SET_OBJECTS:
      return {
        ...state,
        photos: action.objects.map(
          ({id, title, imageUri}) => ({
            id: id.toString(),
            title,
            image: imageUri,
            description: ''
          })
        ),
      };
    case ADD_PHOTO:
      return {
        ...state,
        photos: state.photos.concat(action.photoData),
      };
    default:
      return state;
  }
};

【讨论】:

    【解决方案2】:

    谢谢琳达·派斯特。您的回答给了我宝贵的反馈。我实际上按照你说的做了很多错别字,但我的错误最终是我的组件中的 console.log(state.photos.photos) 。老实说,我把那部分删掉了,所以你无法解决它。

    Tl;dr:你不能 console.log 一个组件内部的 redux 内部状态。我希望这能澄清我的错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-28
      • 2018-10-26
      • 1970-01-01
      • 2021-10-10
      • 2018-05-12
      • 2017-01-24
      • 2019-05-27
      • 2021-11-13
      相关资源
      最近更新 更多