我有两个React组件Posts和Postform。帖子是显示从api获取的帖子列表的组件。 Postform组件是一种创建新帖子然后更新Post组件的表单。我在Posts中声明了一个函数addPost()作为全局函数,并将其绑定在Posts构造函数中。 然后,从Posts中导出addPost()方法,并将其导入Postform组件中,在这里我想使用导入的addPost()方法来更新Posts组件的状态
但是我收到一条错误消息,指出这在Post组件的addPost()内部无效 此blog post
进行了从另一个同级更新同级的过程。我同时提供了两个组件的代码以供参考。
这是Posts.js,即
import React, { Component } from 'react'
export function addPost(posts){
this.setState({ posts });
}
export default class Posts extends Component {
constructor(props) {
super(props);
this.state = {
posts: []
}
this.getPosts = this.getPosts.bind(this);
addPost = addPost.bind(this);
}
getPosts(posts) {
this.setState({ posts, })
console.log(this.state);
}
componentWillMount() {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(res => res.json())
.then(posts => this.getPosts(posts));
}
render() {
const posts = this.state.posts;
const postList = posts.map(post => {
return (
<div key={post.id}>
<div>ID: {post.id}</div>
<br />
<div>{post.title}</div>
<br />
<div>{post.body}</div>
<hr />
</div>
)
})
return (
<div>
<h1>Posts</h1>
<hr />
{postList}
</div>
)
}
}
这是Postform.js
import React, { Component } from 'react'
import addPost from './Posts.js';
export default class Postform extends Component {
constructor(props) {
super(props);
this.state = {
title: '',
body : '',
}
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
onChange(event) {
this.setState({
[event.target.name]: event.target.value,
})
}
onSubmit(event) {
const post = {
title: this.state.title,
body : this.state.body
}
//this is going to start a fetch process to post the new post to the database
fetch('https://jsonplaceholder.typicode.com/posts',
{
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(post),
})
.then(res => res.json())
.then(data => addPost({data}));
event.preventDefault();
}
render() {
return (
<div>
<h1>ADD POST</h1>
<form onSubmit={this.onSubmit}>
<div>
<label>Title</label>
<input type="text" name="title" value={this.state.title} onChange={this.onChange} />
</div>
<div>
<label>Body</label>
<textarea name="body" onChange={this.onChange} value={this.state.body} />
</div>
<br />
<button type="submit">ADD</button>
</form>
</div>
)
}
}
答案 0 :(得分:0)
问题在于以下几行:
export function addPost(posts){
this.setState({ posts });
}
这将不起作用,因为this
类之外没有Post
的概念。您应该在父组件(Postform
)中有一个函数,并以此方式更新道具。