【问题标题】:How to filter or find a string in an array of strings如何在字符串数组中过滤或查找字符串
【发布时间】:2021-06-05 09:53:12
【问题描述】:

我正在尝试使用字符串属性从 Mongo Atlas 中过滤集合:namesurls

然后我尝试保存过滤后的值,从 Mongo 存储和检索,并将其发送回另一个组件。

我收到 500 内部服务器错误。我试图以过滤后的数组名称为目标,我只返回完整数组而不是过滤器的结果。我已经在我的 express 服务器上添加了一个 name 属性,一切似乎都正常。

我的目标是使用过滤器water 来显示匹配的图像并在另一个组件中使用该值,然后再次过滤并访问匹配的图像。

我成功地在显示 name:waterfall <div>name:{urlName}</div 的名称数组映射函数中返回过滤后的名称,但是我没有成功将相同的 过滤值 发送到 monogo。

另外,我尝试注释掉setName(response.data.name);,但它返回:TypeError: Cannot read property 'filter' of undefined 单击保存按钮时。

Gallery.js 反应

import React, { useState, useEffect } from "react";
import { useHistory } from "react-router-dom";
import { isExpired, decodeToken } from "react-jwt";
import Input from "../../Reuseables/reusableInput/Input";
import Container from "react-bootstrap/Container";
import Card from "react-bootstrap/Card";
import Button from "react-bootstrap/Button";
import Form from "react-bootstrap/Form";
import "../css/waterfall.css";
import axios from "axios";

  const Waterfall = () => {
  const [body, setBodyInput] = useState("");
  const [title, setTitleInput] = useState("");
  const [id, setId] = useState("");
  const [url, setUrl] = useState([]);
  const [name, setName] = useState([]);

  const history = useHistory();

  function makeRequest(e) {
    e.preventDefault();
    //gets data from inputs and sends to backend
    axios({
      method: "POST",
      url: "http://localhost:5000/getinput",
      data: {
        body: body,
        title: title,
        // name: name,
      },
    }).then((response) => {
      setId(response.data.data._id);
      // setName(response.data.name);
      console.log(response.data);
    });
  }

  const loadImage = async () => {
    try {
      let res = await axios.get("http://localhost:5000/geturls");
      console.log(res.data)
      setUrl(res.data.map(d=>d.url)); // array of urls
      setName(res.data.map(n=>n.name)); //array of names
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    // console.log("use effect working!");
    // function checks login
    }
    loadImage();
  },[history]);

  return (
    <div className="waterfall">
      <Container className="mt-5 ml-auto mr-auto">
        <h1 className="text-center"> Post to
          <span className="text-success"> ShareVerse</span>
        </h1>
        <Form className="shadow p-3 mb-5 bg-white rounded">
          <Form.Group controlId="formBasicVerse">
          <Form.Label> 
              <h5>Verse Title</h5>
            </Form.Label>
            <Input setInputValue={setTitleInput} 
                   inputValue={title} 
                   inputName={'title'}
                   inputType={"text"}
          />          
            </Form.Group>

          <Form.Group controlId="formBasicVerse">
            <Form.Label>
              <h5>Verse Body:</h5>
            </Form.Label>
            <Input setInputValue={setBodyInput}  
                   inputValue={body} 
                   inputName={'body'}
                   inputType={"text"}
          />      
          </Form.Group>
          <div className="">
            <Card className="bg-dark text-white">
            {name.filter(name => name.includes('water')).map((urlName) => (
            <div>name:{urlName}</div>
            ))}
            
            {url.filter(name => name.includes('water')).map((urlData) => (
            <Card.Img name={url.name} src={urlData} alt="Card image" />
            ))}
              <Card.ImgOverlay> 
                <Card.Title className="text-center mt-5">
                  <h1>{title}</h1>
                </Card.Title>
                <Card.Title className="text-center mt-5">{body}</Card.Title>
              </Card.ImgOverlay>
            </Card>
            <div>
              <Button 
                  className=" saveImageBtn mt-3" 
                  type="submit" onClick={makeRequest}
              > Save
              </Button>

              <div>
              <Button
                className=" saveImageBtn mt-3"
                href={`http://localhost:3000/getverse/${id}`}
              >
                View Post!
              </Button>
              </div>
            </div>
          </div>
        </Form>
      </Container>
    </div>
  );
};

export default Waterfall;

GalleryController.js

exports.PostGalleryInput = async (req, res) => {
    console.log(req.body)
    // res.send("recieved");
    await new Posts(req.body).save( async (err, data) => {
      if (err) {
        // if there is an error send the following response
        res.status(500).json({
          message: "Something went wrong, please try again later.",
        });
      } else {
        // if success send the following response
        res.status(200).json({
          message: "Post Created",
          data,
        });
      }
    });
  };

【问题讨论】:

  • 当您尝试在 MongoDB 中保存记录时,似乎会引发问题/错误。您是否有权查看该错误是什么?
  • @DrewReese 感谢您的回复。我的后端终端没有错误,但是当我单击保存 if setName(response.data.name);没有被注释掉
  • @Ajeet Shah,谢谢您的回复,我想发送一个过滤后的名称数组,数组中有 14 个名称,其中一个名称为“水”,我想要将该值发送到后端。后端名称的值为字符串
  • 所以name 应该是字符串而不是数组?这似乎与您将 name 状态设置为响应结果的另一个错误一致......如果它现在是一个字符串,则您无法映射它。 NM,您说它在响应中未定义。
  • @DrewReese 我确定标题和正文工作,我添加了 name 属性以发布到后端,url 和 name 来自我在 atlas 中手动编写的集合。在前端我得到全名数组,我试图只得到过滤后的值,但我不知道语法。

标签: arrays reactjs mongoose


【解决方案1】:

我认为后端 API 期望负载中的 name 字符串而不是字符串数组。

所以,你可以这样做:names.find(name =&gt; name === "water")

const [names, setNames] = useState([]); // For simplicity, use plural here i.e. names

function makeRequest(e) {
  e.preventDefault();
  axios({
    method: "POST",
    url: "http://localhost:5000/getinput",
    data: {
      body: body,
      title: title,
      name: names.find(name => name === "water"), // Here
    },
  }).then((response) => {
    setId(response.data.data._id);
    console.log(response.data);
  });
}

现在,您可以在其中使用变量(例如,如果它存储在任何状态变量中),而不是硬编码 water

【讨论】:

  • 成功了,名字是瀑布而不是水,我只是用“水”过滤
猜你喜欢
  • 1970-01-01
  • 2017-03-22
  • 2020-06-19
  • 2022-01-13
  • 2022-07-04
  • 2016-01-11
  • 1970-01-01
  • 1970-01-01
  • 2019-05-02
相关资源
最近更新 更多