【问题标题】:Working with state objects in Redux (basic)在 Redux 中使用状态对象(基础)
【发布时间】:2016-06-07 16:53:48
【问题描述】:

我是 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())
  }
}

这是我的减速器

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

  switch (action.type) {

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

    default:
      return state
  }
}

如果您需要任何其他信息,请告诉我。我只有在使用exampleState = 'this is my message!'时才能让它工作

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

【问题讨论】:

  • 与 state 或 redux 无关。这是一个 React 错误,很可能出现在 App 中。你能给我们看看吗?
  • 特别是ShowTweetComponent似乎
  • 当然,我已经在描述中添加了一个链接。如果您想了解更多信息,请告诉我。我已经查看了错误引用的位置,但我自己无法理解问题
  • 我认为您正在尝试渲染一个数组(在 html 中显示整个状态?)并反应抱怨它不可能这样做。因此建议使用map 来显示单个值。在模板中显示您的状态时是否尝试过使用Array.map
  • 谢谢您的回答,听起来好像是正确的。目前只是稍微努力实际实施,但如果我成功了会告诉你

标签: javascript reactjs state redux


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2021-06-17
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-26
    相关资源
    最近更新 更多