如何在反应中从json文件中获取数据?

Posted

技术标签:

【中文标题】如何在反应中从json文件中获取数据?【英文标题】:how to get data from json file in react? 【发布时间】:2017-05-11 16:33:45 【问题描述】:

我正在使用redux-thunk 从 json 文件中获取数据。我关注这个 url

https://github.com/gaearon/redux-thunk 我收到此错误

中间件不是函数

你能告诉我如何从 json 文件中获取数据并显示在组件中

这是我的代码 https://plnkr.co/edit/R6TCNcK4kUaRkTDpObQN?p=preview

const thunk =ReduxThunk;
const abc= (state=0,action) => 
  console.log('in redux', action.type)
  switch(action.type)
    case 'INC':

      return state +1
    case 'DEC':
      return state -1
      default :
      return state;
  

const createStore,bindActionCreators ,applyMiddleware  =Redux;
const Provider,connect =ReactRedux;

const store = createStore(abc,
applyMiddleware(thunk)
);


class First extends React.Component 
  constructor (props)
    super(props);
    this.state =
    digit :0  
    
  
  inc ()
    console.log('ince', this.props)
    this.props.increment();
  

  dec ()
    console.log('dec')
    this.props.decrement();
  
  getDate()

  
  render()
    return (
    <div>
        <button onClick=this.inc.bind(this)>INCREMENT</button>
        <p>this.props.digit</p>
        <button onClick=this.dec.bind(this)>DECREMENT</button>
        <button onClick=this.getDate.bind(this)>GET DATA</button>
      </div>
    )
  
 

const actions = 
    increment: () => 
        return 
            type: 'INC',
        
    ,
     decrement: () => 
        return 
            type: 'DEC',
        
    
;

const AppContainer = connect(
    function mapStateToProps(state) 
        return 
            digit: state
        ;
    ,
    function mapDispatchToProps(dispatch) 
        return bindActionCreators(actions, dispatch);
    
)(First);
ReactDOM.render(
   <Provider store=store>
    <AppContainer/>
  </Provider>
  ,document.getElementById('root'))

【问题讨论】:

【参考方案1】:

你快到了。

只需将第一行替换为:

const thunk = ReduxThunk.default;

他们改变了导出方式,并在他们的github readme上提到了这一点

【讨论】:

能否请您更改 plunker 并从文件中获取数据 更新了插件:plnkr.co/edit/OfwSHVj8Y1in1wOQgeTy?p=preview 如果你想包含来自另一个文件的 JSON,要么使用 import/export 和模块捆绑器,要么只在 html 文件中使用脚本标签,并为 src 属性提供文件的路径(我在 plunker 做的,因为那里没有任何模块捆绑器) thunk 有什么用 这个问题在here上有一个很好的答案

以上是关于如何在反应中从json文件中获取数据?的主要内容,如果未能解决你的问题,请参考以下文章

如何在本机反应中从 json 获取数据?

如何在反应中从文件中加载数据?

如何在反应应用程序中从数据库中获取和显示图像

laravel 在多行中插入数据,并在一个循环中从 API 获取 [关闭]

如何在 Laravel 中从多对多关系的一对多关系中获取项目?

LARAVEL 在文件上传中从 isValid 获取错误