如何在组件中打印数组 - ReactJS

时间:2018-03-02 21:00:52

标签: javascript jquery html reactjs

这是StoryCreator的代码

import React from 'react'

import { Helmet } from 'react-helmet'
import { connect } from 'react-redux'
import { Layout, Row, Col, Form, Input, Button, Divider, message, Icon, AutoComplete } from 'antd'
import { Link } from 'react-router-dom'
import ErrorPopover from '../../components/ErrorPopover/ErrorPopover'
import { success } from '../../services/story.services'

import { changeStoryTitle, changeStoryContent , changeStoryBody, changeStoryImage, changeStoryCategoryid, sendStory } from '../../actions/story.actions'
import { fetchCategories } from '../../actions/category.actions'

import '../../vendor/Shadow/Shadow.css'
import '../../vendor/Radius/Radius.css'
import './StoryCreator.css'

const { Content } = Layout
const FormItem = Form.Item
const { TextArea } = Input;
const onload = () => {
  const hide = message.loading('Cargando entrada..');
};

class StoryCreator extends React.Component {

  componentWillMount() {
    this.props.dispatch(fetchCategories())
  }

  constructor (props) {
    super(props)
  }

  handleChange = (e) => {
    if(e.target.id === 'storyTitle') {
      this.props.dispatch(changeStoryTitle(e.target.value))
    }
  }

  handleChangeContent = (e) => {
    if(e.target.id === 'storyContent') {
      this.props.dispatch(changeStoryContent(e.target.value))
    }
  }

  handleChangeBody = (e) => {
    if(e.target.id === 'storyBody') {
      this.props.dispatch(changeStoryBody(e.target.value))
    }
  }

  handleChangeImage = (e) => {
    if(e.target.id === 'storyImage') {
      this.props.dispatch(changeStoryImage(e.target.value))
    }
  }

  handleChangeCategoryid = (e) => {
    if(e.target.id === 'storyCategoryid') {
      this.props.dispatch(changeStoryCategoryid(e.target.value))
    }
  }

  handleSubmit = (e) => {
    e.preventDefault()

    let storyTitleVal = this.props.storyTitle
    let storyContentVal = this.props.storyContent
    let storyBodyVal = this.props.storyBody
    let storyImageVal = this.props.storyImage
    let storyCategoryidVal = this.props.storyCategoryid

    if (!storyTitleVal) {
      this.storyTitleInput.focus()
      return
    }

    this.props.dispatch(sendStory(storyTitleVal, storyContentVal, storyBodyVal, storyImageVal, storyCategoryidVal), onload)
  }

  render () {

    const {categories} = this.props;
    const data = categories;

    function Complete() {
      return (
        <FormItem style={{marginTop: '-10px'}} label='CATEGORY'>
        <AutoComplete
          style={{ width: 200 }}
          dataSource={data}
          placeholder="try to type `b`"
          filterOption={(inputValue, option) => option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1}
        />
        </FormItem>

      );
    }
    return (
      <div>
        <Form onSubmit={this.handleSubmit}>
          <FormItem label='TITLE'>
            <Input id='storyTitle' value={this.props.storyTitle} onChange={this.handleChange} ref={(input) => { this.storyTitleInput = input }} size='large' />
          </FormItem>

          <FormItem style={{marginTop: '-10px'}} label='CONTENT'>
            <Input id='storyContent' value={this.props.storyContent} onChange={this.handleChangeContent} ref={(input) => { this.storyContentInput = input }} size='large' />
          </FormItem>

          <FormItem style={{marginTop: '-10px'}} label='Body'>
          <TextArea rows={4} id='storyBody' value={this.props.storyBody} onChange={this.handleChangeBody} ref={(input) => { this.storyBodyInput = input }} size='large'  />
          </FormItem>

          <FormItem style={{marginTop: '-10px'}} label='IMAGE'>
            <Input id='storyImage' value={this.props.storyImage} onChange={this.handleChangeImage} ref={(input) => { this.storyImageInput = input }} size='large' />
          </FormItem>

          <FormItem style={{marginTop: '-10px'}} label='CATEGORY'>
            <Input id='storyCategoryid' value={this.props.storyCategoryid} onChange={this.handleChangeCategoryid} ref={(input) => { this.storyCategoryidInput = input }} size='large' />
          </FormItem>

          <Complete />

          <Button onClick={onload} disabled={this.props.isBusy} style={{marginTop: '-10px'}} type='primary' size='large' htmlType='submit' className='shadow-1'>
            Send
          </Button>
        </Form>
      </div>
    )
  }

}

function mapStateToProps (state) {
  const { isBusy } = state.appReducer
  const { storyTitle, storyContent, storyBody, storyImage, storyCategoryid } = state.storyReducer

  return {
    isBusy,
    storyTitle,
    storyContent,
    storyBody,
    storyImage,
    storyCategoryid,
    categories
  }
}

const StoryCreatorConnected = connect(mapStateToProps)(StoryCreator)
export default StoryCreatorConnected

和这个category.actions

之一

import { CATEGORY_CHANGE_NAME, CATEGORIES_FETCHED, CATEGORY_DELETED } from "../constants/category.constants";
import { showLoading, hideLoading } from 'react-redux-loading-bar'
import { toggleBusy } from '../actions/app.actions'
import { SaveCategory, GetCategories, DeleteCategory, UpdateCategory } from '../services/category.services'
import { history } from '../helpers/history'

export const deleteCategory = (id) => {
    return { type: CATEGORY_DELETED, id: id}
}

export const changeNameCategory = (name) => {
    return { type: CATEGORY_CHANGE_NAME, name: name}
}

export const sendCategory = (name) => {
    return dispatch => {
        dispatch(toggleBusy(true))
        dispatch(showLoading())
        SaveCategory(name)
        .then(
            response => {
                dispatch(toggleBusy(false))
                dispatch(hideLoading())
                dispatch(changeNameCategory(''))
                dispatch(fetchCategories())
            },
            error => {
                dispatch(toggleBusy(false))
                dispatch(hideLoading())
            }
        )
    }
}

export const updateCategory = (id, name) => {
    return dispatch => {
        dispatch(toggleBusy(true))
        dispatch(showLoading())
        dispatch(changeNameCategory(''))
        history.push('/admin/category')
        UpdateCategory(id, name)
        .then(
            response => {
                dispatch(toggleBusy(false))
                dispatch(hideLoading())
                dispatch(changeNameCategory(''))
                dispatch(fetchCategories())
            },
            error => {
                dispatch(toggleBusy(false))
                dispatch(hideLoading())
            }
        )
    }

}

export const destroyCategory = (id) => {
    return dispatch => {
        dispatch(toggleBusy(true))
        dispatch(showLoading())
        DeleteCategory(id)
        .then(
            response => {
                dispatch(toggleBusy(false))
                dispatch(hideLoading())
                dispatch(fetchCategories())
            },
            error => {
                dispatch(toggleBusy(false))
                dispatch(hideLoading())
            }
        )
    }
}


export const fetchCategories = () => {
    return dispatch => {
        dispatch(toggleBusy(true))
        dispatch(showLoading())
        GetCategories()
        .then(
            response => {
                console.log(response)
                dispatch(toggleBusy(false))
                dispatch(hideLoading())
                dispatch(success(response.categories))
            },
            error => {
                console.log(error)
                dispatch(toggleBusy(false))
                dispatch(hideLoading())
            }
        )
    }

    function success(categories) { return { type: CATEGORIES_FETCHED, categories: categories}}
}

它所做的是与服务进行通信以便能够获取所有已加载的类别,问题是我无法将所有这些类别放在变量中以便能够在自动完成中列出它们,我不知道如何将数组加载到变量中。

奇怪的是,我之前可以在另一个列出所有类别的组件中执行此操作。在那里我留下了代码,希望你能帮助我

import React from 'react'
import {connect} from 'react-redux'
import {
  Card,
  Alert,
  Icon,
  Button,
  Table,
  Divider,
  Popconfirm
} from 'antd';
import {Link} from 'react-router-dom'
import {fetchCategories, destroyCategory, editCategory} from '../../actions/category.actions';
const {Meta} = Card;


class Categories extends React.Component {
  componentDidMount() {
    this.props.dispatch(fetchCategories())
  }
  handleDeleteCategory(e) {
    //var removedItem = fruits.splice(pos, 1);
    this.props.dispatch(destroyCategory(e.id))
  }


  render() {
    const {categories} = this.props;
    const data = categories;

    const columns = [
      {
        title: 'ID',
        dataIndex: 'id',
        key: 'id'
      }, {
        title: 'Nombre de la categoria',
        dataIndex: 'name',
        key: 'name'
      }, {
        title: 'Acciones',
        key: 'action',
        render: (text, record) => (<span>
           <Link to={`/admin/category/edit/${record.id}/${record.name}`}>Editar</Link>
          <span className="ant-divider"/>
          <a onClick={() => this.handleDeleteCategory(record)}>Eliminar</a>
        </span>)
      }
    ];

    if (this.props.categories.length == 0)
      return (<Alert message="No hay categorias para mostrar." type="error"/>);

    return <Table dataSource={data} columns={columns}/>

  }

}

function mapStateToProps(state) {
  const {categories} = state.categoryReducer
  return {categories}
}

const connectedCategories = connect(mapStateToProps)(Categories)
export default connectedCategories

1 个答案:

答案 0 :(得分:0)

解决它,忘记将变量导入mapStateToProps并减少。谢谢!