Javascript ReactJS-如何更新道具中属性的数据?

Javascript ReactJS-如何更新道具中属性的数据?,javascript,reactjs,Javascript,Reactjs,我有一个帖子列表,每个帖子都有一个按钮,如果用户真的想删除相应的帖子,它会显示一个模式窗口并确认 当用户确认后,数据被发送到后端,删除相应的帖子并返回一组所有帖子。但是,当尝试更新前端的帖子列表时,我遇到以下错误: Posts.jsx:61 Uncaught (in promise) TypeError: _this2.props.posts is not a function 此行出现此错误: this.props.posts(res.data); Home.jsx import Reac

我有一个帖子列表,每个帖子都有一个按钮,如果用户真的想删除相应的帖子,它会显示一个模式窗口并确认

当用户确认后,数据被发送到后端,删除相应的帖子并返回一组所有帖子。但是,当尝试更新前端的帖子列表时,我遇到以下错误:

Posts.jsx:61 Uncaught (in promise) TypeError: _this2.props.posts is not a function
此行出现此错误:

this.props.posts(res.data);
Home.jsx

import React from "react";
import Posts from './Posts';
import NewPost from './NewPost';
import axios from 'axios';
import Moment from 'react-moment';
import LoadModal from './LoadModal';

class Home extends React.Component {
    constructor(props) {
        super(props);

      this.state = {
        posts: [],
            loading: true
       };
    }

    componentDidMount() {
        axios.get('/posts')
            .then(response => {
                console.log('---');
                console.log(response.data);
                console.log('---');
            this.setState({ posts: response.data, loading: false });
          });
    }

    render() {
        return (
            <div>
                <Posts posts={this.state.posts} loading={this.state.loading} />
            </div>
        )
    }
}
export default Home
import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
import {Collapse} from 'react-collapse';
import classNames from "classnames";
import Dialog from 'react-bootstrap-dialog';


class Posts extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            activeIndex: null,
            removePostBtn: 'Remove'
        }
    }

    onClick(post_id) {
        this.dialog.show({
            title: 'Remove Post - #'+post_id,
            body: 'Do you really want to remove this post?',
            actions: [
                Dialog.CancelAction(),
                Dialog.DefaultAction(
                    this.state.removePostBtn,
                    () => {
                        this.setState({ removePostBtn: 'Removing...' }, () => {
                            axios.get('/remove_post/'+post_id, { post_id: post_id })
                            .then(res => {
                                this.props.posts(res.data); // here's the error
                            })
                        })
                    },
                    'btn-danger'
                )
            ],
        })
    }

  render () {
        let content;
        const { activeIndex } = this.state;
        const Button = require('react-bootstrap').Button;

        if (this.props.loading) {
            content = 'Loading...';
        } else {
                content = this.props.posts.map((post, index) => {
                return(
                  <li key={index}>
                    <div>   
                        <span>{post.id}</span>
                        <span>{post.message}</span>
                        <Button onClick={() => this.onClick(post.id)}>Show alert</Button>
                        <Dialog ref={(el) => { this.dialog = el }} />
                    </div>
                  </li>
                )
            });

        }
    return (
      <div>
        <h1>Posts!</h1>
        <div className="row">
            <div className="col-md-6">
                <ul>
                    {content}
                </ul>
            </div>
        </div>
      </div>
    );
  }
}

export default Posts
从“React”导入React;
从“./Posts”导入帖子;
从“./NewPost”导入NewPost;
从“axios”导入axios;
从“反应力矩”导入力矩;
从“./LoadModal”导入LoadModal;
类Home扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
员额:[],
加载:正确
};
}
componentDidMount(){
axios.get(“/posts”)
。然后(响应=>{
console.log('--');
console.log(response.data);
console.log('--');
this.setState({posts:response.data,load:false});
});
}
render(){
返回(
)
}
}
导出默认主页
Posts.jsx

import React from "react";
import Posts from './Posts';
import NewPost from './NewPost';
import axios from 'axios';
import Moment from 'react-moment';
import LoadModal from './LoadModal';

class Home extends React.Component {
    constructor(props) {
        super(props);

      this.state = {
        posts: [],
            loading: true
       };
    }

    componentDidMount() {
        axios.get('/posts')
            .then(response => {
                console.log('---');
                console.log(response.data);
                console.log('---');
            this.setState({ posts: response.data, loading: false });
          });
    }

    render() {
        return (
            <div>
                <Posts posts={this.state.posts} loading={this.state.loading} />
            </div>
        )
    }
}
export default Home
import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
import {Collapse} from 'react-collapse';
import classNames from "classnames";
import Dialog from 'react-bootstrap-dialog';


class Posts extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            activeIndex: null,
            removePostBtn: 'Remove'
        }
    }

    onClick(post_id) {
        this.dialog.show({
            title: 'Remove Post - #'+post_id,
            body: 'Do you really want to remove this post?',
            actions: [
                Dialog.CancelAction(),
                Dialog.DefaultAction(
                    this.state.removePostBtn,
                    () => {
                        this.setState({ removePostBtn: 'Removing...' }, () => {
                            axios.get('/remove_post/'+post_id, { post_id: post_id })
                            .then(res => {
                                this.props.posts(res.data); // here's the error
                            })
                        })
                    },
                    'btn-danger'
                )
            ],
        })
    }

  render () {
        let content;
        const { activeIndex } = this.state;
        const Button = require('react-bootstrap').Button;

        if (this.props.loading) {
            content = 'Loading...';
        } else {
                content = this.props.posts.map((post, index) => {
                return(
                  <li key={index}>
                    <div>   
                        <span>{post.id}</span>
                        <span>{post.message}</span>
                        <Button onClick={() => this.onClick(post.id)}>Show alert</Button>
                        <Dialog ref={(el) => { this.dialog = el }} />
                    </div>
                  </li>
                )
            });

        }
    return (
      <div>
        <h1>Posts!</h1>
        <div className="row">
            <div className="col-md-6">
                <ul>
                    {content}
                </ul>
            </div>
        </div>
      </div>
    );
  }
}

export default Posts
从“React”导入React;
从“react dom”导入react dom;
从“axios”导入axios;
从'react Collapse'导入{Collapse};
从“类名”中导入类名;
从“反应引导对话框”导入对话框;
类发布扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
activeIndex:null,
removePostBtn:“删除”
}
}
onClick(post_id){
this.dialog.show({
标题:“删除帖子-#”+帖子id,
正文:“你真的想删除此帖子吗?”,
行动:[
Dialog.CancelAction(),
Dialog.DefaultAction(
this.state.removepostbn,
() => {
this.setState({removePostBtn:'Removing…'),()=>{
get('/remove_post/'+post_id,{post_id:post_id})
。然后(res=>{
this.props.posts(res.data);//这里是错误
})
})
},
“btn危险”
)
],
})
}
渲染(){
让内容;
const{activeIndex}=this.state;
const Button=require('react-bootstrap')。按钮;
如果(本道具装载){
内容='加载…';
}否则{
content=this.props.posts.map((post,index)=>{
返回(
  • {post.id} {post.message} this.onClick(post.id)}>显示警报 {this.dialog=el}}/>
  • ) }); } 返回( 帖子!
      {content}
    ); } } 导出默认帖子

    如何使用
    帖子正确更新
    道具

    您不能直接更新任何道具。您需要在父组件中创建一个更新处理程序来更新
    this.state.posts

    import React from "react";
    import Posts from './Posts';
    import NewPost from './NewPost';
    import axios from 'axios';
    import Moment from 'react-moment';
    import LoadModal from './LoadModal';
    
    class Home extends React.Component {
      constructor(props) {
        super(props);
    
        this.state = {
          posts: [],
          loading: true
        };
      }
    
      componentDidMount() {
        this.getPosts();
      }
    
      getPosts = () => {
        axios.get('/posts')
        .then(response => {
          console.log('---');
          console.log(response.data);
          console.log('---');
          this.setState({ posts: response.data, loading: false });
        });
      }
    
      updatePosts = posts => {
        this.setState({ posts });  
      }
    
      render() {
        return (
          <div>
            <Posts posts={this.state.posts} loading={this.state.loading} getPosts={this.getPosts} updatePosts={this.updatePosts} />
          </div>
        )
      }
    }
    export default Home
    
    import React from 'react';
    import ReactDOM from 'react-dom';
    import axios from 'axios';
    import {Collapse} from 'react-collapse';
    import classNames from "classnames";
    import Dialog from 'react-bootstrap-dialog';
    
    
    class Posts extends React.Component {
      constructor(props) {
        super(props);
    
        this.state = {
          activeIndex: null,
          removePostBtn: 'Remove'
        }
      }
    
      onClick(post_id) {
        this.dialog.show({
          title: 'Remove Post - #'+post_id,
          body: 'Do you really want to remove this post?',
          actions: [
            Dialog.CancelAction(),
            Dialog.DefaultAction(
              this.state.removePostBtn,
              () => {
                this.setState({ removePostBtn: 'Removing...' }, () => {
                axios.get('/remove_post/'+post_id, { post_id: post_id })
                .then(res => {
                  //this.props.posts(res.data); // here's the error
                  // Call parent function to re-retch posts
                  this.props.getPosts();
                  // Or direclty pass data to update the parent state
                  this.props.updatePosts(res.data);
                })
              })
           },
            'btn-danger'
            )
          ],
        })
      }
    
      render () {
        let content;
        const { activeIndex } = this.state;
        const Button = require('react-bootstrap').Button;
    
        if (this.props.loading) {
          content = 'Loading...';
        } else {
          content = this.props.posts.map((post, index) => {
              return(
          <li key={index}>
            <div>
              <span>{post.id}</span>
              <span>{post.message}</span>
              <Button onClick={() => this.onClick(post.id)}>Show alert</Button>
              <Dialog ref={(el) => { this.dialog = el }} />
            </div>
          </li>
        )
        });
    
        }
        return (
          <div>
            <h1>Posts!</h1>
            <div className="row">
              <div className="col-md-6">
                <ul>
                  {content}
                </ul>
              </div>
            </div>
          </div>
        );
      }
    }
    
    export default Posts
    
    从“React”导入React;
    从“./Posts”导入帖子;
    从“./NewPost”导入NewPost;
    从“axios”导入axios;
    从“反应力矩”导入力矩;
    从“./LoadModal”导入LoadModal;
    类Home扩展了React.Component{
    建造师(道具){
    超级(道具);
    此.state={
    员额:[],
    加载:正确
    };
    }
    componentDidMount(){
    这是getPosts();
    }
    getPosts=()=>{
    axios.get(“/posts”)
    。然后(响应=>{
    console.log('--');
    console.log(response.data);
    console.log('--');
    this.setState({posts:response.data,load:false});
    });
    }
    updatePosts=posts=>{
    this.setState({posts});
    }
    render(){
    返回(
    )
    }
    }
    导出默认主页
    从“React”导入React;
    从“react dom”导入react dom;
    从“axios”导入axios;
    从'react Collapse'导入{Collapse};
    从“类名”中导入类名;
    从“反应引导对话框”导入对话框;
    类发布扩展了React.Component{
    建造师(道具){
    超级(道具);
    此.state={
    activeIndex:null,
    removePostBtn:“删除”
    }
    }
    onClick(post_id){
    this.dialog.show({
    标题:“删除帖子-#”+帖子id,
    正文:“你真的想删除此帖子吗?”,
    行动:[
    Dialog.CancelAction(),
    Dialog.DefaultAction(
    this.state.removepostbn,
    () => {
    this.setState({removePostBtn:'Removing…'),()=>{
    get('/remove_post/'+post_id,{post_id:post_id})
    。然后(res=>{
    //this.props.posts(res.data);//这里是错误
    //调用父函数以重新检索帖子
    this.props.getPosts();
    //或直接传递数据以更新父状态
    this.props.updatePosts(res.data);
    })
    })
    },
    “btn危险”
    )
    ],
    })
    }
    渲染(){
    让内容;
    const{activeIndex}=this.state;
    const Button=require('react-bootstrap')。按钮;
    如果(本道具装载){
    内容='加载…';
    }否则{
    content=this.props.posts.map((post,index)=>{
    返回(
    
  • {post.id} {post.message} this.onClick(post.id)}>显示警报 {this.dialog=el}}/>
  • ) });