健全文件未显示

Sanity documents not showing

每当我使用 'createOrReplace' 理智地创建一个新文档时。它成功创建了文档,但是它没有在主屏幕上显示新创建的文档。

注意:我从 Sanity Studio 上传的所有其他文档都正确显示。只有使用 'createOrReplace' 创建的未显示

如果你想查看,这是我的代码:

Home.js

import { 
    View, 
    StyleSheet,
    Image,
    TouchableOpacity,
    ScrollView
} 
from 'react-native';
import React, { 
    useState,
    useEffect
 } 
from 'react';
import { 
    client, 
} 
from '../lib/client';
import CustomHeader from '../components/CustomHeader.component';
import Post from '../components/Post.component';

const Home = ({ navigation }) => {

  const [posts, setPosts] = useState([]);

    useEffect(() => {
        querySelector();
    })

  const querySelector = async () => {
      const query = `*[_type == 'post']`
      const post = await client.fetch(query);

      setPosts(post);
  }

  return (
      <>
      /* <CustomHeader screenName="Home" back={false} height={150} />
      <TouchableOpacity style={{
          position: "absolute",
          marginTop: 80,
          marginLeft: 40
      }}
      onPress={() => navigation.navigate("Create")}
      >
          <Image style={{
              height: 30,
              width: 30,
          }} source={require("../assets/Main/plus.png")} />
      </TouchableOpacity> */

     // Commented out code blocks are not necessary, the main topic is the sanity query

    <ScrollView>
        <View style={{
            display: "flex",
            flexDirection: "row",
            flexWrap: "wrap"
        }}>
            {
                posts.map(
                    post => {
                        return(
                            <>
                            <View style={{
                                display:"flex",
                                flexDirection: "row"
                            }}>
                                <Post title={post.title} desc={post.description} image={post.image} id={post._id} />
                            </View>
                            </>
                        )
                    }
                )
            }
        </View>
    </ScrollView>
    </>
  )
}

export default Home;

Create.js

import { 
    View, 
    Text, 
    StyleSheet, 
    TouchableOpacity, 
    Image, 
    Platform,
    TextInput,
    Dimensions,
    Alert
} 
from 'react-native';
import React, { 
    useState 
} 
from 'react';
import { 
    SafeAreaView 
} 
from 'react-native-safe-area-context';
import * as ImagePicker from 'expo-image-picker';
import { storage } from '../firebase/firebase-config';

const CreatePosts = ({ navigation }) => {

    const tokenWithWriteAccess = "my token";

    const [image, setImage] = useState(null);
    const [imageURL, setImageURL] = useState(null);
    const [title, setTitle] = useState('');
    const [desc, setDesc] = useState('');

    const pickImage = async () => {
        // No permissions request is necessary for launching the image library
        let result = await ImagePicker.launchImageLibraryAsync({
          mediaTypes: ImagePicker.MediaTypeOptions.All,
          allowsEditing: true,
          aspect: [1, 1],
          quality: 1,
        });
    
        if (!result.cancelled) {
          setImage(result);
        }

        const blob = await new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            xhr.onload = () => {
              resolve(xhr.response);
            };
            xhr.onerror = (e) => {
              reject(new TypeError("Network request failed"));
            };
            xhr.responseType = "blob";
            xhr.open("GET", image.uri, true);
            xhr.send(null);
        });

        
  const metadata = { contentType: "image/jpg" };

  const imgRef = storage.ref(`${title == null ? "No" : title}/fileName`);

  await imgRef.put(blob, metadata);

  blob.close();
 
  // Image permanent URL 
  const imgURL = await imgRef.getDownloadURL();

  setImageURL(imgURL)
      };

      const createPost = async () => {
        if(title || desc !== ""){
            const mutations = [{
                createOrReplace: {
                  _id: 'p.',
                  _type: 'post',
                  title: title,
                  description: desc,
                  image: imageURL
                }
              }]
              
              await fetch(`https://projectIdHidden.api.sanity.io/v2021-06-07/data/mutate/production`, {
                method: 'post',
                headers: {
                  'Content-type': 'application/json',
                  Authorization: `Bearer ${tokenWithWriteAccess}`
                },
                body: JSON.stringify({mutations})
              })
            } else {
                return Alert.alert(
                    "Error",
                    "Please enter the title and the description"
                )
            }
        }

  return (
    <>
    <Image style={styles.background} source={require('../assets/Main/Gradiants/gradient_img.png')} />
        <SafeAreaView style={styles.androidSafeAreaView}>
            <View style={styles.container}>
                <Text style={styles.header}>
                    New Post {title == "" ? "" : `"${title}"`}
                </Text>
                <TextInput placeholder='Your Title' style={styles.title} value={title} onChangeText={text => setTitle(text)} />
                    <TextInput placeholder='Your Description' style={styles.desc} value={desc} onChangeText={text => setDesc(text)} />
                        <TouchableOpacity style={styles.imgContainer} onPress={pickImage}>
                            <Image style={styles.img} source={image == null ? require("../assets/Main/select.png") : { uri: image.uri } } />
                        </TouchableOpacity>
                            <TouchableOpacity style={image == null ? styles.postDisabled : styles.post} disabled={image == null ? true : false} onPress={createPost}>
                                    <Text style={styles.postTxt}>
                                        Post!
                                    </Text>
                        </TouchableOpacity>
                        <TouchableOpacity style={styles.cancel} disabled={image == null ? true : false} onPress={() => navigation.navigate("Home")}>
                                    <Text style={styles.cancelTxt}>
                                        Cancel
                                    </Text>
                        </TouchableOpacity>
                    </View>
        </SafeAreaView>
    </>
  )
}

const styles = StyleSheet.create({
    //Styles not required
})

export default CreatePosts;

您正在将文档放在 non-root path (_id: ‘p.’) 上,这将需要令牌才能查看。