【问题标题】:how to get data from json file in react?如何在反应中从json文件中获取数据?
【发布时间】: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'))

【问题讨论】:

    标签: reactjs react-router react-redux redux-thunk


    【解决方案1】:

    你快到了。

    只需将第一行替换为:

    const thunk = ReduxThunk.default;
    

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

    【讨论】:

    • 能否请您更改 plunker 并从文件中获取数据
    • 如果你想包含来自另一个文件的 JSON,要么使用 import/export 和模块捆绑器,要么只在 html 文件中使用脚本标签,并为 src 属性提供文件的路径(我在 plunker 做的,因为那里没有任何模块捆绑器)
    • thunk 有什么用
    • 这个问题在here上有一个很好的答案
    猜你喜欢
    • 2021-05-23
    • 2021-03-21
    • 2019-07-14
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多