gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 06:47:10 25 4
gpt4 key购买 nike

我是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com