javascript - 在 Redux 中使用状态对象(基本)

标签 javascript reactjs state redux

我是 Redux/React 新手,在使用状态对象时遇到问题。

我已经按照下面的index.js初始化了我的状态,但收到了这个错误

Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {text}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of ShowTweetComponent.

index.js

const initialState = {
  text: 'test successful'
} 

let store = createStore( 
  twitterApp,       
  initialState,     
  applyMiddleware(  
    thunkMiddleware 
  )
) 

console.log('1 - index.js loaded')

render( 
    <Provider store={store}>
      <App />
    </Provider>,
    document.getElementById('LoadApp')
)

这是我的行动

function getTweetData(json) {
  return {
    type: REQUEST_TWEETS,
    tweet: json.status_text,
    receivedAt: Date.now().toString()
  }
}

function fetchTweets() {

  return dispatch => {
    return fetch(`/api/twitter`)
      .then(response => response.json())
      .then(json => dispatch(getTweetData(json)))
  }


}

export function fetchTweetsIfNeeded() {
  return (dispatch, getState) => {
    return dispatch(fetchTweets())
  }
}

这是我的 reducer

const displayData = (state = [], action) => {

  switch (action.type) {

    case REQUEST_TWEETS:
      return [
        ...state,
        {
          text: action.tweet
        }
      ]

    default:
      return state
  }
}

如果您需要任何额外信息,请告诉我。我只能在使用 exampleState = 'this is my message!'

时才能使其工作

更新: 这是存储库(请参阅客户端文件夹以获取 react 内容)https://github.com/jaegerbombb/twitter-api-test

最佳答案

您正在使用您的 redux 状态(在 twitterContainer.js 中)覆盖 this.props.children。我不确定这是否是一个好主意。 React 期望 children 是一个 node,但它正在获取一个数组(来自您的 twitterApp reducer )。

对于您的代码,您只需将 children 键更改为 twitterContainer.jstwitterComponent.js 中的另一个名称

关于javascript - 在 Redux 中使用状态对象(基本),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37685060/

相关文章:

javascript - 当有多个按钮使用相同功能时,使用单击处理程序更改按钮的颜色

javascript - React JS View 不会在 setState() 上重新渲染

javascript - useEffect 钩子(Hook)在初始渲染时调用,无需更改依赖项

javascript - 用新值更新现有的 JS 关联数组

javascript - 对 CouchDB 中的哈希数组进行 Map/Reduce

javascript - 在 React 中物化输入不会触发 onChange?

javascript - 对多个字段进行数组过滤

javascript - 使用 Javascript 为焦点上的文本框设置类

javascript - 对象/命名空间和自调用函数

reactjs - Redux-Saga中如何实现回调?