2017-10-10 202 views
0
this.state = { 
    post: { 
     question: '', 
     img: '', 
     postId: '', 
     userId: '' 
     }, 
    feed: [], 
    } 

將對象添加到數組的最佳做法是什麼?將對象添加到數組的最佳做法

+0

第一:不'POST'必須是一個數組?第二:如果'post'數組中有多個項目,您如何決定更改'question'值的哪一個? –

+0

每個帖子都有一個Id – Omar

+0

這裏似乎有幾個腥味的東西。如果'post'是一個帖子數組,則稱其爲'posts',否則不需要將其放入數組中。其次,你正在使用'setState'這個事實告訴我這個狀態是組件的內部狀態,並且這裏的更新沒有發出任何類型的HTTP請求。如果是這樣的話,你可能應該有另一個名爲'Post'的組件來處理單個帖子的狀態,而不是試圖更新組件內狀態數組。 – Damon

回答

2

首先,你需要一些修正與state

this.state = { 
    posts: [], 
    feeds: [], 
} 

在未來帖子將是一個Array of Objects例如:

this.state = { 
    posts: [ 
    { postid: 1, question: "question" }, 
    { postid: 2, question: "question" } 
    ] 
} 

使用this.setState添加一個新的崗位,以崗位,也請記住state不可變

const newpost = { id: 1, question: "question" }; 
this.setState({ 
    posts: this.state.posts.concat(newpost) 
    // or with rest operator posts: [...this.state.posts, newpost] 
}) 

進一步瞭解stateReact State

一個例子的jsfiddle

class Example extends React.Component { 
 
    constructor(props) { 
 
    super(props); 
 
    this.state = { 
 
     posts: [], 
 
     feed: [], 
 
    } 
 
    } 
 

 
    getName =() => { 
 
    const names = ['One', 'Two', 'Three', 'Four', 'Five', 'Six'] 
 
    const random = Math.floor(Math.random() * names.length); 
 
    return names[random] 
 
    }; 
 
    
 
    getId =() => Math.floor(Math.random() * (9999-1)) + 1; 
 
    
 
    makePost =() => ({ id: this.getId(), name: this.getName() }); 
 
    
 
    createPost =() => { 
 
    this.setState({ 
 
     // Rest operators ensure a new object with merged properties and values. 
 
     // Requires the "transform-object-rest-spread" Babel plugin 
 
     posts: [...this.state.posts, this.makePost()] 
 
     // Or like this: this.state.posts.concat(this.makePost()) 
 
    }) 
 
    }; 
 
    
 
    render() { 
 
    
 
    return (
 
    <div> 
 
     <button onClick={this.createPost}>Create Post</button> 
 
     <pre> 
 
     {JSON.stringify(this.state, null, 2)} 
 
     </pre> 
 
    </div> 
 
    ); 
 
    } 
 
} 
 

 
ReactDOM.render(
 
    <Example />, 
 
    document.getElementById('container') 
 
);
<div id="container"> 
 
    <!-- This element's contents will be replaced with your component. --> 
 
</div> 
 

 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>