【问题标题】:How to map React components but have 2 different sources of info如何映射 React 组件但有 2 个不同的信息源
【发布时间】:2021-05-30 11:01:05
【问题描述】:

您好,我想提供有关学校的信息并上传学校/课程的图片

我有不同状态的图像 URL 和信息,因为图像保存在 S3 上,而信息在 postgres 中。结果,我有 2 条不同的路线。

由于地图功能只允许一个项目,我如何访问这两条信息来呈现组件?

反应


    useEffect(() => {
        async function requestSchools() {
            await axios.get("http://localhost:4000/api/getschool").then(response => {
                console.log(response.data)
                setSchools(response.data.rows)
            })

            await axios.get("http://localhost:4000/api/getschoolimages").then(response => {
                console.log(response.data)
                setImageKey(response.data.Contents)
            })
        }
        requestSchools();

        let doubleArr = [[], []]
        doubleArr[0].push(schools)
        doubleArr[1].push(imageKey)

        console.log('doubleArr', doubleArr)

        setSchools(doubleArr);

        return schools
    }, []);

    console.log('schools Correct', schools)


    //console.log(schools)


    const renderSchools = (school, index) => {
        return (
            <div>
                <InfoCard
                    key={index}
                    id={index}
                    name={school.name}
                    about={school.about}
                    location={school.location}
                    admission={school.admission}
                    identifier={index + 1}
                    url={imageKey[index]}

                />
            </div>

        )
    }

    return (
        <div>
            <Link to="/additem">
                <button className="ret_btn">Create</button>
            </Link>
            <div>{schools.map(renderSchools)}</div>
        </div>

    )

后台

schoolRouter.get('/getschool', async function (req, res) {
    try {
        const allschools = await pool.query(`SELECT * FROM school`);
        console.log('allschools', allschools.rows)
        const imageKeys = s3.listObjects(params, function (err, data) {
            if (err) console.log('error', err, err.stack); // an error occurred
            else console.log(data);
        })
        res.json(allschools)
    } catch (err) {
        console.error(err.message)
    }

})




schoolRouter.get('/getschoolimages', async function (req, res) {
    try {
        //console.log('allschools', allschools.rows)
        const imageKeys = s3.listObjects(params, function (err, data) {
            if (err) console.log('error', err, err.stack); // an error occurred
            else res.send(data);
        })
        //res.json(allschools)
    } catch (err) {
        console.error(err.message)
    }

})

信息卡

import Button from 'react-bootstrap/Button';
import Card from 'react-bootstrap/Card';
import 'bootstrap/dist/css/bootstrap.min.css';
import '../stylesheets/cardstyles.css';
import { BrowserRouter, Route, Switch, Link, Redirect } from 'react-router-dom';



const InfoCard = (props) => {
    const url = `https://dreamschools-bucket.s3.amazonaws.com/${props.url}`
    return (
        <div className="container spacer">
            <div className="row align-items-center gen-card">
                <div className="col-12 col-md-6"><img width="100%" alt="Grandfather with child" src={url} sizes="(max-width: 200x) 80vw, 200px" /></div>
                <div className="col-12 col-md-6 gen-card">
                    <h3>{props.name}</h3>
                    <p>{props.about}</p>


                    <Link to={{
                        pathname: `/allinfo/${props.identifier}`,
                        param1: {
                            name: props.name,
                            about: props.about,
                            location: props.location,
                            admission: props.admission,
                            id: props.identifier
                        }
                    }}>
                        <button className="btn btn-primary my-3 btn-block">More information</button>
                    </Link>

                    <Link to={{
                        pathname: `/edititem/${props.identifier}`,
                        param1: {
                            name: props.name,
                            about: props.about,
                            location: props.location,
                            admission: props.admission,
                            id: props.identifier
                        }
                    }}>
                        <button className="btn btn-primary my-3 btn-block">Edit</button>
                    </Link>

                    {/*  <a className="btn btn-primary my-3 btn-block" href="/contact/">Edit</a> */}

                </div>
            </div>
        </div>
    )
}


export default InfoCard

【问题讨论】:

    标签: javascript node.js reactjs express


    【解决方案1】:

    我会将image 添加为school 对象的属性,例如:

    // it looks like you have the same order in both since I see you have `imageKey[idx]` in your example
    const schoolsWithImage = schools.map((school, idx) => {...school, image: images[idx]})
    
    setSchools(schoolsWithImage)
    

    那么你可以在循环时使用school.image

    【讨论】:

    • 我很抱歉,但是 ... 到底是什么意思,我收到了错误声明或预期声明
    • ... 是 javascript 中的扩展运算符。它把后面提到的变量对象的所有元素都传到左边的赋值变量中
    • 语法不正确,可能会导致错误。要直接从 map 函数返回 JavaScript 对象,我们必须将其包裹在括号内: const schoolWithImage =schools.map((school, idx) => ({...school, image: images[idx]}))
    • 是的,抱歉,对象周围缺少( )
    【解决方案2】:

    如果顺序正确,您可以只使用索引作为键来获取正确的值,如果顺序不正确,您将必须有一个共享标识符,最有效的方法是执行一个循环并合并相应的对象,或者非常无效的方法是为地图中的每次迭代找到正确的图像,它会为您提供“更清洁”的代码,但会导致地图的每次迭代都有一个额外的循环。虽然第一个代码多一点,但更有效。

    并更改您的异步功能

    let school = await axios.get("http://localhost:4000/api/getschool")
    
    let schoolimages = await axios.get("http://localhost:4000/api/getschoolimages")
     setSchools(school.data.rows)
     setImageKey(schoolimages.data.Contents)
    

    测试一下,告诉我结果如何

    【讨论】:

    • 顺序正确并且确实尝试将其传递到我的代码中,但是当我传递索引时我一直不确定
    • 我可能是错的,但你不使用then 和等待?更新了我的答案尝试一下并告诉我它是如何进行的,这将在您设置状态之前等待两个等待承诺都完成,并确保两个状态都已定义
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-29
    • 2014-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-22
    相关资源
    最近更新 更多