我在列表中显示数组时遇到问题。
我的 Ajax 请求的响应看起来像这样:
[{"id":"1","counter":"1"},{"id":"2","counter":"2"},{"id":"3","counter":"3"}]
我的操作代码:
export default function getItems(){
return (dispatch, getState) => {
return dispatch (fecthItem())
}
}
function fecthItem(){
return dispatch => {
// dispatch(requestPost())
return fetch('http://localhost:444/localWebServices/getCounter.php')
.then(response => response.json())
.then(json => dispatch(receivePosts(json)))
}
}
function receivePosts(json){
console.log("receivePosts");
var items = [];
console.log(json.map( x => x.counter))
// var items = json.map( x => x.counter);
for (var i = 0, len = json.length; i < len; i++) {
console.log(json[i].counter);
items.push(json[i].counter)
}
return {
type: 'RECEIVE_POSTS',
items: items
}
}
我的 Reducer - getItem:
export default (state = [], action) => {
switch (action.type){
case 'RECEIVE_POSTS':
return [
...state,
{
text: action.items
}
]
default:
return state
}
}
目前显示结果,但我无法显示每个结果 自己的列表行。
渲染代码以显示结果:
<ul>
{this.props.items.map((items, i) => <li key={i}>{items.text} </li>)}
</ul>
谁能告诉我必须更改哪些内容才能在列表中正确显示这些项目?
更新:
这是来 self 的开发控制台的 Img。我想我以错误的方式创建了数组,您怎么看?
这是我的整个组件,它应该呈现列表,也许它有帮助:)
import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
export default class TodoList extends Component {
render() {
const posts = this.props.todos
console.log(this.props.items)
const items = this.props.items
const isEmpty = posts.length === 0
return (
<div>
<h3>Meine Aufgaben</h3>
<ul>
{this.props.items.map((items, i) => <li key={i}>{items.text}</li>)}
</ul>
<ul>
{isEmpty
? <h3>Sie haben noch keinen Todo´s angelegt</h3>
: <h3>Ihre Ergebnisse</h3>
}
{this.props.todos.map((todo, i) => <li key={i}>{todo.text}</li>)}
</ul>
</div>
)
}
}
const mapStateToProp = state => ({todos: state.addItem, items: state.getItem})
export default connect (mapStateToProp)(TodoList)
这是 React 扩展的输出:
更新:
好的。我想这个错误是非常基本的,因为当我用给定的索引尝试这个时,项目显示正确:
{this.props.items.map((items) => <li key={items.text}>{items.text[0]}</li>)}
那我怎么能跑过去呢?
最佳答案
你应该在你的 reducer 中返回对象而不是数组
export default (state = [], action) => {
switch (action.type){
case 'RECEIVE_POSTS':
return Object.assign({}, state, {
items: action.items
});
//return {
// ...state,
// items: action.items
//}
default:
return state
}
}
然后你可以通过
渲染你的项目{ this.props.items.items && this.props.items.items.length &&
this.props.items.items.map((item, i) => <li key={i}>{item}</li>)}
关于javascript - 数组未正确显示在列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37655010/