简体   繁体   English

如何将值从状态传递到另一个组件

[英]How to pass values from a state to another component

I have two pages on my react app.我的 React 应用程序上有两页。 One page allows you to submit a post, and the second page shows all of the posts.一页允许您提交帖子,第二页显示所有帖子。 I need to be able to retrieve the data from the state on one page, but I am receiving an error.我需要能够从一页上的状态中检索数据,但我收到一个错误。 What am I doing wrong to display this, because I thought I could use props to gather the state from my post page.显示这个我做错了什么,因为我认为我可以使用道具从我的帖子页面收集状态。

My Display Post Page:我的显示帖子页面:

import React from 'react';
import './App.css';


export default class Scroll extends React.Component {


    render() {
        return (

            <div className="flex-container">
                <div className="post">
                    {this.props.displayPost(this.props.state.posts)}
                </div>
            </div>
        );
    }
}

My post page:我的帖子页面:

import React from 'react';
import axios from 'axios';
import './App.css';
import { post } from '../../routes/routes';

export default class PersonList extends React.Component {

    state = {
        title: "",
        body: "",
        posts: []
    };

    componentDidMount = () => {
        this.getPost();
    }

    getPost = () => {
        axios.get("http://localhost:5000/posts/save")
            .then((response) => {
                const data = response.data;
                this.setState({ posts: data });
                console.log("Data has been recieved")
            })
            .catch(() => {
                alert("Error recieving data")
            })
    }

    handleChange = (event) => {
        const target = event.target;
        const name = target.name;
        const value = target.value;

        this.setState({
            [name]: value
        })
    };

    submit = (event) => {
        event.preventDefault();

        const payload = {
            title: this.state.title,
            body: this.state.body,
        }

        axios({
            url: 'http://localhost:5000/posts/save',
            method: 'POST',
            data: payload,
        })
            .then(() => {
                console.log('Data sent to the server');
            })
            .catch(() => {
                console.log('Internal server error');
            });
    };

    displayPost = (posts) => {
        if (!post.length) return null;

        return posts.map((post, index) => {
            <div key={index}>
                <h3 id="post-text">{post.title}</h3>
                <p id="post-text">{post.body}</p>
            </div>
        });
    }

    render() {
        console.log("State ", this.state)
        return (
            <div className="flex-container-home">
                <div className="app">
                    <form onSubmit={this.submit}>
                        <input
                            placeholder="title"
                            type="text"
                            name="title"
                            value={this.state.title}
                            onChange={this.handleChange}
                        />
                        <textarea placeholder="description"
                            name="body"
                            cols="30" rows="10"
                            value={this.state.body}
                            onChange={this.handleChange}
                        >
                        </textarea>
                        <button>Submit</button>
                    </form>
                </div>
            </div>
        )
    }
}

Here is working example:这是工作示例:

import React from "react";

export default class PersonList extends React.Component {
  state = {
    title: "",
    body: "",
    posts: [],
  };

  componentDidMount = () => {
    this.getPost();
  };

  getPost = () => {
    this.setState({ posts: ["post1", "post2", "post3"] });
  };      

  displayPost = (posts) => {
    if (!posts || !posts.length) return null;

    return posts.map((post, index) => (
      <div key={index}>
        <p>{post}</p>
      </div>
    ));
  };

  render() {
    return (
      <div className="App">
        <Scroll displayPost={this.displayPost} posts={this.state.posts} />
      </div>
    );
  }
}

class Scroll extends React.Component {
  render() {
    return (
      <div className="post">
        Posts: {this.props.displayPost(this.props.posts)}
      </div>
    );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将 state 值从组件传递到另一个包含参数设置的子组件? - How to pass state values from a component into another child component that contains param settings? 如何将状态从有状态组件传递到另一个有状态组件 - How to pass state from a stateful component to another stateful component 如何保留新状态值并将其传递给ReactJS中的另一个路由器组件 - How to retain and pass the new state values to another router component in ReactJS 如何从自定义组件到另一个父组件获取状态值 - How to get state values from custom component to another parent component 如何在React js中将状态从一个组件传递到另一个组件? - How to pass state from one component to another in React js? 如何将 state 变量的值从一个组件传递到另一个组件? - How to pass value of state variable from one component to another? 如何将值从一个组件传递到另一个组件? - How can I pass values from one component to another component? 在 ReactJs 中将 state 从一个组件传递到另一个组件 - Pass state from one component to another in ReactJs 如何通过 state 在 useNavigate 到另一个组件 - How to pass state in useNavigate to another component 如何将 useState state 传递给另一个组件? - How to pass useState state to another component?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM