gpt4 book ai didi

javascript - 理解 Redux 和状态

转载 作者:行者123 更新时间:2023-11-30 21:05:47 25 4
gpt4 key购买 nike

我已经上了两门类(class),treehouse 和一门关于 udemy,关于 react/redux 的类(class),就在我对自己说“嘿,你明白了,我们来做一些练习吧”时,我遇到了一些我看不到的大错误诊断。

我在这里尝试做的事情听起来很简单,而且在普通的 javascript 中它可以工作。我的状态是一个空对象 state = {},当调用我的操作时,它会在状态 noteName 中创建一个数组。所以在一天结束时状态应该看起来像 state = { noteName: [ ...state.noteName, action.payload]}

当我 console.log(this.props.inputvalue) 时,它将返回 input 元素中的任何内容。我以为我了解对象,因为控制台日志应该返回数组 noteName 而不是实际值,对吗?

代码

actions/index.js

export const INPUT_VALUE = 'INPUT_VALUE';

export function addNoteAction(text) {
return {
type: INPUT_VALUE,
payload: text
}
}

reducers/reducer_inputvalue.js

import { INPUT_VALUE } from '../actions';

// state is initialized as an empty object here
export default function(state = {}, action) {
switch (action.type) {
case INPUT_VALUE:
state.noteName = [];
// this SHOULD create an array that concats action.payload with
// whatever is already inside of state.name
return state.noteName = [...state.noteName, action.payload];
default:
return state;
}
}

noteitems.js

import React, { Component } from 'react';
import { connect } from 'react-redux';

class NoteItems extends Component {
render() {
return (
<ul>
{
this.props.inputvalue.noteName
?
this.props.inputvalue.noteName.map((note, index) => {
// this should iterate through noteName but returns undefined
return <li key={index}>{note}</li>;
})
:
<li>Nothing here</li>
}
</ul>
);
}
}

function mapStateToProps(state) {
return {
inputvalue: state.inputvalue
}
}

export default connect(mapStateToProps)(NoteItems);

最佳答案

这是因为每次调度操作 INPUT_VALUE 时,您都在重置 noteName。 redux 的主要原则是不修改状态,而是在当前的基础上创建一个新的状态。在你的情况下:

const initialState = {
noteName: []
};

export default function(state = initialState, action) {
switch (action.type) {
case INPUT_VALUE: return {
noteName: [...state.noteName, action.payload]
};

default: return state;
}
}

关于javascript - 理解 Redux 和状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46627232/

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